My Blog

PHP: get and set custom HTTP headers

5.01.2012 | Blog, PHP

In this short tutorial I will illustrate how can you send and read custom HTTP headers using php.

First let’s start by sending a custom HTTP header to the server. I will be using cURL library to send HTTP requests.

Sending The Request Header

Let’s say our custom header name is ‘Authorization’ and we want to set its value to ’123456′, now create a file named http-request.php with the following content:

$uri = 'http://localhost/http.php';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
	CURLOPT_HTTPHEADER	=> array('Authorization: 123456'),
	CURLOPT_RETURNTRANSFER	=>true,
	CURLOPT_VERBOSE		=> 1
));
$out = curl_exec($ch);
curl_close($ch);
// echo response output
echo $out;

Now we have sent the request with method POST. The CURLOPT_VERBOSE option is used for debugging when you want to output the request headers and the response headers. You shall remove it on production.

Reading the custom header

Now let’s create the reads that custom header sent from the curl request. create a file named http.php with the following contents

print_r(apache_request_headers());

Now execute the http-request.php using cli to watch the debug output.
Now if you are lucky enough you will see the Authorization header as below:

Array
(
    [Host] => localhost
    [Accept] => */*
    [Authorization] => 123456
    [Content-Length] => 9
    [Content-Type] => application/x-www-form-urlencoded
)

Oh, What if I’m not lucky? then you have PHP installed as CGI and have got php < 5.4 . People who have PHP installed as an Apache module or have PHP version 5.4 are the lucky ones, but don't worry I've got your back.

Custom Headers with PHP CGI

To work around this we will have to play around with the .htaccess but you will need mod_rewrite.


    RewriteEngine On
    RewriteRule .? - [E=Authorization:%{HTTP:Authorization}]

What are we doing up there? Well we are reading the HTTP header named ‘Authorization’ by %{HTTP:Authorization} and setting it as an environment variable with the E so it will be accessible by the $_SERVER superglobal. Also make sure that the rule is right after the ‘RewriteEngine On’ statement to avoid conflicts.

Now try this in the http.php:

echo $_SERVER['Authorization'];

Voila!

Reference:
Environment Variables in Apache

Be Sociable, Share!

Comments