By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Cookie Handling and HTTP Requests in PHP

This php tutorial shows how to handle cookies in php – be prepared to rule the internet with HTTP requests.

Edited: 2016-01-03 18:08

Last: HTTP Requests and Redirects in PHP

To remember cookies delivered by the server when performing HTTP Requests in PHP, you will need to cycle trough the http response headers. One way to do this, is by using a while loop to check for "Set-Cookie" headers, and this is the method we will use in this tutorial on php.

The first thing you will need to do, is to perform a http request for a cookie delivering source. Before you spend to much time making a cookie delivering script – Brugbart already have one setup that you can use for testing purposes. The below php script will request a file called cookie-delivery.php, we will show you how to save the cookies later in the Tutorial.

$sURL = "http://brugbart.com/Examples/cookie-delivery.php"; // The Request URL

$aHTTP['http']['method']          = 'GET';
$aHTTP['http']['header']          = "User-Agent: My PHP Script\r\n";
$aHTTP['http']['header']         .= "Referer: http://brugbart.com/\r\n";

$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;

Right now this script won't show you any cookies on its own, so lets proceed onto the cookie handling part of this tutorial.

Saving Cookies Delivered by the Server

The cookies that are delivered by the server will be available in the response headers, specifically the "Set-Cookie" headers – and there may be multiple of those present in the response headers – so to get them all, we will need to cycle trough the response header array. We will be using use a loop to do this, we used a while loop in this Tutorial, but you can use whatever you prefer!

The response headers from HTTP requests, made with functions such as file_get_contents and fread, are available in the $http_response_header array, we cycle trough this array with our loop. But to best handle cookies, its easier if we make a couple of functions – the first function is shown below, this function will save cookies to the Cookies directory – you should create this directory in the same dir as your php script.

function SaveCookies($aRH) {
  $n = count($aRH); // Number of Pieces
  $counter = 0;
  while ($counter <= $n) {
    if(preg_match('@Set-Cookie: (([^=]+)=[^;]+)@i', $aRH["$counter"], $matches)) {
      $fp = fopen('Cookies/'.$matches["2"].'.txt', 'w');
       fwrite($fp, $matches["1"]);
      fclose($fp);
    }
    ++$counter;
  }
}

This function should be called after each http request. Functions will not be explained here, instead you may want to read the php tutorials on functions and function arguments.

See also: Functions in PHP

Delivering cookies back to the server

We will also need to make a function that will read the cookies from the cookie directory, and prepare them to be delivered back to the server. The function should be called before making a http request, we will then check if the cookie header needs to be updated, or if it even needs to be sent (no cookies, no need to send the header.)

function UpdateCookies() {
  $aCookies = glob("Cookies/*.txt");
  $n = count($aCookies);
  if ($n !== 0) {
   $counter = 0;

   while ($counter < $n) {
    $sCombined .= file_get_contents($aCookies["$counter"]) . ';';
    ++$counter;
   }
   return $sCombined;
  } else {
   return $n;
  }
}

The glob function is used to check for cookies in the directory where we save cookies, if any files are found, their content will be added to the $sCombined variable and returned. If no files are found, it will simply return 0, and the cookie header won't be send with the request.

Cookie Handling and HTTP Requests

The following is a fully working example, with functions calls and http request combined.

function UpdateCookies() {
  $aCookies = glob("Cookies/*.txt");
  $n = count($aCookies);
  if ($n !== 0) {
   $counter = 0;

   while ($counter < $n) {
    $sCombined .= file_get_contents($aCookies["$counter"]) . ';';
    ++$counter;
   }
   return $sCombined;
  } else {
   return $n;
  }
}
function SaveCookies($aRH) {
  $n = count($aRH); // Number of Pieces
  $counter = 0;
  while ($counter <= $n) {
    if(preg_match('@Set-Cookie: (([^=]+)=[^;]+)@i', $aRH["$counter"], $matches)) {
      $fp = fopen('Cookies/'.$matches["2"].'.txt', 'w');
       fwrite($fp, $matches["1"]);
      fclose($fp);
    }
    ++$counter;
  }
}

 $sCookie = UpdateCookies(); // Prepare cookies for deliverance
 // 
 // Begin the HTTP Request
 //
$sURL = "http://brugbart.com/Examples/cookie-delivery.php"; // The Request URL

 $aHTTP['http']['method']          = 'GET';
 $aHTTP['http']['header']          = "User-Agent: My PHP Script\r\n";
 $aHTTP['http']['header']         .= "Referer: http://brugbart.com/\r\n";
 if ($sCookie !== 0) { // Send cookies back to server (if any)
 $aHTTP['http']['header']        .= "Cookie: $sCookie\r\n";
 }
 $context = stream_context_create($aHTTP);
 $contents = file_get_contents($sURL, false, $context); // Send the Request
 $ResponseHeaders = $http_response_header;
 SaveCookies($ResponseHeaders); // Saves cookies to cookie directory (if any).

echo $contents;