Question

I'm using this code to get HTTP response:

$url = "http://example.com/";
$headers = get_headers($url);
$header = substr($headers[0], 9, 3);
echo = $header;

which works great but I need to hide referrer so I am using http://href.li/ like so:

$url = "http://href.li/?http://example.com/";
$headers = get_headers($url);
$header = substr($headers[0], 9, 3);
echo = $header;

which results in a 200 OK HTTP status code no matter what the status of the final page is. Is it possible at all to get header from the final page? Or is there another approach to accomplish this while still using a referrer hiding service?

Was it helpful?

Solution

You don't need a third-party service to hide your referer in this kind of request, you can set it to whatever you need, however, you cannot do it with the get_headers function. You could do it with file_get_contents and stream_context_create. In your case, I imagine it would be something like this:

$URL = 'http://example.com/';
$Context = stream_context_create(array(
    'http' => array(
        'method' => 'HEAD',
        'header' => 'Referer: '
    )
));
file_get_contents($URL, false, $Context);
$ResponseHeaders = $http_response_header;

$header = substr($ResponseHeaders[0], 9, 3);
echo $header;

stream_context_create creates a stream context with whatever options for the request that you specify and file_get_contents does the request using that context. Afterwards the script checks $http_response_header which is a kind of a magic variable that is populated after HTTP requests to HTTP URLs and it is available only in the local scope, i.e., right after you call the function making the HTTP request but not, say, in another function that gets executed afterwards. The content of $http_response_header is basically the same as the result of get_header() function.

(You can also use GET in the above example but if you don't need the response body, HEAD just gets the headers without the body. By the way, PHPs get_headers issues a GET request that fetches the whole response including the body which then gets discarded. But sometimes the receiving server or script cannot handle HEAD requests or does some actions differently compared to a GET request - you should really try it out and see what works for you.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top