Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP GET Request, sending headers

Tags:

php

I need to perform a get request and send headers along with it. What can I use to do this?

The main header I need to set is the browser one. Is there an easy way to do this?

like image 735
James Jeffery Avatar asked Jun 13 '10 14:06

James Jeffery


People also ask

How do I view headers in PHP?

The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request.

What does the function Headers_sent () in PHP return?

The headers_sent() function is an inbuilt function in PHP which is used to determines whether the header is successfully sent or not. The headers_sent() function returns True if header sent successfully and False otherwise.

How do I get all headers?

you can use getallheaders() to get an array of all HTTP headers sent. Show activity on this post. Every HTTP request header field is in $_SERVER (except Cookie ) and the key begins with HTTP_ . If you're using Apache, you can also try apache_request_headers .


2 Answers

If you're using cURL, you can use curl_setopt ($handle, CURLOPT_USERAGENT, 'browser description') to define the user-agent header of the request.

If you're using file_get_contents, check out this tweak of an example on the man page for file_get_contents:

// Create a stream $opts = array(   'http'=>array(     'method'=>"GET",     'header'=>"Accept-language: en\r\n" .               "Cookie: foo=bar\r\n" .               "User-agent: BROWSER-DESCRIPTION-HERE\r\n"   ) );  $context = stream_context_create($opts);  // Open the file using the HTTP headers set above $file = file_get_contents('http://www.example.com/', false, $context); 
like image 90
grossvogel Avatar answered Sep 17 '22 18:09

grossvogel


If you are requesting a page, use cURL.

In order to set the headers (in this case, the User-Agent header in the HTTP request, you would use this syntax:

<?php $curl_h = curl_init('http://www.example.com/');  curl_setopt($curl_h, CURLOPT_HTTPHEADER,     array(         'User-Agent: NoBrowser v0.1 beta',     ) );  # do not output, but store to variable curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);  $response = curl_exec($curl_h); 
like image 25
amphetamachine Avatar answered Sep 19 '22 18:09

amphetamachine