Fetching a URL with Arbitrary Headers






Fetching a URL with Arbitrary Headers

Problem

You want to retrieve a URL that requires specific headers to be sent with the request for the page.

Solution

Set the header stream context option when using the http stream as in Figure. The header value must be a single string. Separate multiple headers with a carriage return and newline (\r\n inside a double-quoted string).

Sending a header with the http stream

<?php
$url = 'http://www.example.com/special-header.php';
$header = "X-Factor: 12\r\nMy-Header: Bob";
$options = array('header' => $header);
// Create the stream context
$context = stream_context_create(array('http' => $options));
// Pass the context to file_get_contents()
print file_get_contents($url, false, $context);
?>

With cURL, set the CURLOPT_HTTPHEADER option to an array of headers to send, as shown in Figure.

Sending a header with cURL

<?php
$c = curl_init('http://www.example.com/special-header.php');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_HTTPHEADER, array('X-Factor: 12', 'My-Header: Bob'));
$page = curl_exec($c);
curl_close($c);
?>

With HTTP_Request, use the addHeader( ) method, as shown in Figure.

Sending a header with HTTP_Request

<?php
require 'HTTP/Request.php';

$r = new HTTP_Request('http://www.example.com/special-header.php');
$r->addHeader('X-Factor',12);
$r->addHeader('My-Header','Bob');
$r->sendRequest();
$page = $r->getResponseBody();
?>

Discussion

cURL has special options for setting the Referer and User-Agent request headers'CURLOPT_REFERER and CURLOPT_USERAGENT. Figure uses each of these options.

Setting Referer and User-Agent with cURL

<?php
$c = curl_init('http://www.example.com/submit.php');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_REFERER, 'http://www.example.com/form.php');
curl_setopt($c, CURLOPT_USERAGENT, 'cURL via PHP');
$page = curl_exec($c);
curl_close($c);
?>

See Also

Documentation on on the http stream wrapper at http://www.php.net/wrappers.http, on curl_setopt( ) at http://www.php.net/curl-setopt, and on the PEAR HTTP_Request class at http://pear.php.net/package/HTTP_Request. The mailing-list message at http://lists.w3.org/Archives/Public/ietf-http-wg-old/1996MayAug/0734.html explains the ambitious and revolutionary goals behind spelling "Referer" with one "r."



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows