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 = '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 Example 13-22.

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 Example 13-35.

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(); ?>

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('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); ?>

13.4.4. 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."




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

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net