<style>
	pre {
		font-size: 0.85em !important;
	}
</style>

cURL is a library for sending data between URLs. You can think of it as a sort of Ajax. Many operating systems have a `curl` command, which allows you to send and receive data remotely, and many programming languages include a cURL library to do the same within the program.

PHP includes cURL in the form of a number of `curl_` functions; it has yet to implement an object-oriented version, though there are some third party libraries available for that.

The basic outline of a cURL transaction looks something like this:

```php
$url = … ;
$curlHandle = curl_init($url);

//	set up some data and a few options

$response = curl_exec($curlHandle);
curl_close($curlHandle);
```

As you see, the cURL session is represented in what is called a cURL handle.

The URL should be an absolute URL, preferably, of course, using HTTPS. If you’re working between URLs on the same host, you can use something like:

```php
$url = "https://{$_SERVER['HTTP_HOST']}/something.php";
```

where `$_SERVER['HTTP_HOST']` resolves to the current host.

In this article, we’re going to set up a front end, the code which makes the cURL requests, and a back end, which will respond to the requests.

An important part of this will be to get the back end to remember the previous request. For this, we’ll need to work with PHP sessions.

##	The Back End

For our back end, we’ll write some code to respond to one of two requests: `init` and `test`:

```php
<?php
//	back-end.php

	if(isset($_GET['init'])) {
		//	initialise and remember some data
		//	output the data just for good measure
	}

	if(isset($_GET['test'])) {
		//	output the data
	}
?>
```

The `init` request will initialise and remember something. By way of feedback, we’ll also output some data, but that’s not really necessary. The `test` request will simply output the data.

The way to remember data between requests is to use PHP sessions:

```php
<?php
//	back-end.php

	session_start();
	session_regenerate_id();
	
	//	etc
?>
```

We start the session as usual (`session_start()`) and regenerate the id to be safe (`session_regenerate_id()`).

With the session activated, we can then use the `$_SESSION` array to store and retrieve the data:

```php
<?php
//	back-end.php

	session_start();
	session_regenerate_id();

	if(isset($_GET['init'])) {
		$_SESSION['remember'] = $_GET['remember'];
		$_SESSION['token'] = uniqid();
		exit(json_encode([
			'sessionid' => session_id(),
			'token' => $_SESSION['token'],
			'remember' => $_SESSION['remember'],
		]));
	}

	if(isset($_GET['test'])) {
		exit(json_encode([
			'sessionid' => session_id(),
			'token' => $_SESSION['token'],
			'remember' => $_SESSION['remember'],
		]));
	}
?>
```

The `$_GET` array represents the URL query string. For the `init` request we use:

```php
$url = "https:// … ?init&remember=something";
```

The `$_GET` array will contain an empty `init` key as well as a `remember` key with the value to be remembered.

When we want to retrieve the remembered value, we’ll use:

```php
$url = "https:// … ?test";
```

The `$_GET` array will contain an empty `test` key.

Just for testing purposes, we’ve also generated a random token. We also output the session id, the token, and the original data to be remembered. The simplest way to output compound data such as an array is to use `json_encode()`.

##	Initialising the Data

At the front end, we’ll first use cURL to call the back end with the data to be remembered:

```php
<?php
//	front-end.php

//	Set Remembered Value
	$value = uniqid();

//	Set up cURL Handle
	$url = "https://{$_SERVER['HTTP_HOST']}/back-end.php?init&remember={$value}";
	$curl = curl_init($url);

//	Result will be a string
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//	Execute cURL & get Response
	$response = curl_exec($curl);

//	Decode Response
	$response = json_decode($response, true);
	[$sessionid, $token, $remember]
	= [$response['sessionid'], $response['token'], $response['remember']];

//	Close cURL
	curl_close($curl);

//	Print Results
	print "sessionid: $sessionid, token: $token, remember: $remember";
?>
```

Here’s what’s going on in the script:

1.	First a random value is generated for the variable `$value`.
2.	Next a URL is set up with the `init` request, together with the value to be remembered `remember=${value}`. The cURL session is then initialised with this URL.

	Note that the `init` and `remember` requests are on the URL. This is just for convenience. If you want to do this a little more securely, you can use the POST method and adjust the back end accordingly. We’ll see an example later of using the POST method.

3.	We’re expecting a result, so we’ll set up the `CURLOPT_RETURNTRANSFER` option to enable the return value.
4.	We now actually make the cURL request using the `curl_exec()` function.

	The return value is the response we’re looking for.
	
5.	The response is a single string which will have been JSON encoded from an array of values. We can now decode this string and assign the values to individual variables.
6.	We should now close the cURL session with the `curl_close()` function.

For the most part, we don’t really need any of the return data. We’re only using them to verify that when we test in the next step they are the values we’re expecting.

The exception is the `$sessionid` variable. We _may_ want that, depending on how we go about referencing the session.

##	Referencing a Session

Remember, in the back end we started a PHP session to store the value from the front end. Each separate front end can have its own session data store, with its own distinct id. The question is, how will the front end be able to reference this session?

###	What Normally Happens

The _normal_ procedure, using a normal browser, takes the following steps:

1.	The browse communicates with the back end, possibly with some data.
2.	The back end initiates a PHP session, saves any data needed, and generates a distinct id.
3.	The back end then returns a cookie to the browser with the session id.
4.	Next time, the browser communicates with the back end, including the cookie with the session id.
5.	This time, the back end uses the session id to restore the session data from last time.

	If the session id is invalid, missing, or out of date, the old session data can’t be restored. A new session store will created, without, of course, the original data.
	
6.	The back end _may_ generate a new session id, or it may keep the original. In any case the cookie with session data is returned to the browser for next time.

	From here, we repeat from Step 4 …
	
To make a few points clear, the __cookie__ is the data which travels between the browser and back end which holds the session id. It is typically, though not necessarily, named `PHPSESSID`. It contains no meaningful data — only the id which identifies the session data at the back end.

At the back end the session data is stored somewhere. Typically, though not necessarily, it’s stored in a disk file, though it’s possible to store this in a database. We’ll refer to this stored data as the __session store__.

> Occasionally, you may see the back end data referred to as a cookie, but that’s only to confuse you. The cookie is strictly the data with the session id which travels between the browser and the back end.  
> Of course, the back end can _also_ set other cookies, independent of the session data.

Cookies and browsers have a long history together, and the browser sends and receives cookies as just part of the job. If you’re connecting with the back end from some other process, and not a browser, then the whole cookie thing is another matter. Such as when using Ajax or cURL.

###	Using Cookies from cURL

cURL is used to communicate with the back end without the browser. That means that we can’t rely on the cookie mechanism working automatically.

In the back end, we’ve already anticipated this by sending the session id as part of the return value. If you could rely on the cookie mechanism, you wouldn’t need to do this.

In the front, end we can _construct_ a cookie in code.

First, we’ll set up the basic code to fetch the remembered value:

```php
//	front-end.php

//	…

//	Setup cURL handle
	$url = "https://{$_SERVER['HTTP_HOST']}/testback.php?test";
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//	Create Cookie
	curl_setopt($curl, CURLOPT_HTTPHEADER, [
		"Cookie: PHPSESSID=$sessionid",
	]);

//	Get Data
	$response = curl_exec($curl);
	$response = json_decode($response, true);
	[$sessionid, $token, $remember]
	= [$response['sessionid'], $response['token'], $response['remember']];
	curl_close($curl);

//	Print Results
	print "sessionid: $sessionid, token: $token, remember: $remember";
```

Most of this code is the same. In fact there are only two important differences:

1.	The URL now has the `test` request, which will cause the data to be fetched.
2.	The cookie is created using the `curl_setopt()` function.

	Note that the value of the cookie is in the `$sessionid` variable, which was set from the return result of the initialisation code earlier.
	
At the back end, PHP is expecting to find the session id in the cookie, and doesn’t care how the cookie got there. From there on, it’s just doing its job.

##	Without Cookies




