Recipe 13.4. Fetching a URL with Arbitrary Headers

13.4.1. Problem

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

13.4.2. Solution

Set the header stream context option when using the http stream as in Example 13-20. 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 = ''; $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 Example 13-22.

Sending a header with cURL

<?php $c = curl_init(''); 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 Example 13-35.

Sending a header with HTTP_Request

<?php require 'HTTP/Request.php'; $r = new HTTP_Request(''); $r->addHeader('X-Factor',12); $r->addHeader('My-Header','Bob'); $r->sendRequest(); $page = $r->getResponseBody(); ?>

13.4.3. Discussion

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

Setting Referer and User-Agent with cURL

<?php $c = curl_init(''); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_REFERER, ''); curl_setopt($c, CURLOPT_USERAGENT, 'cURL via PHP'); $page = curl_exec($c); curl_close($c); ?>

13.4.4. See Also

Documentation on on the http stream wrapper at, on curl_setopt( ) at, and on the PEAR HTTP_Request class at The mailing-list message at explains the ambitious and revolutionary goals behind spelling "Referer" with one "r."

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: