Setting HTTP Request Headers With PHP

Setting request headers for HTTP request made trough PHP.

Last: Making HTTP POST Requests Next: Sending HTTP Requests Trough Proxies in PHP

When performing HTTP request using file_get_contents, or similar functions of PHP, setting request headers is done using the stream_context_create. This was also covered briefly in the last php tutorial, but lets show how to add a couple of more headers in this tutorial.

For the purpose of testing, you may use the URL provided in the source code examples. Its a simple PHP script that will output all request headers, useful for the purpose of testing your HTTP requests.

First you need to create the HTTP request – that has been explained in earlier tutorials, so it will not be explained here – the below is a bare example of a simple GET request.

$sURL = "http://brugbart.com/Examples/http-request-headers.php"; // The Request URL
$aHTTP = array(
  'http' => // The wrapper to be used
    array(
    'method'  => 'GET', // Request Method
  )
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);

echo $contents;

The $aHTTP array can be coded as shown in the above example, but a more readable way to code it would be like its coded in the below example:

$aHTTP['http']['method']  = 'GET';

Adding request headers

To add a request header – such as a user agent string – to the php script, simply do like demonstrated in the below example.

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

To add more headers, such as a referer header, simply do like in below example:

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

Additional request headers will be added in the same way, by adding a Carriage return "\r" and line feed "\n" at the end of each header, followed by whatever header you want to add. Once you have added all the headers, you should end up with something looking like the below (full script):

$sURL = "http://brugbart.com/Examples/http-request-headers.php"; // The POST 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;

As you can see, writing the array this way is much more readable than the way we did it in the first tutorials.