Get HTTP header header / redirect status using PHP

Hej there,

I am currently working on a PHP tool to monitor quite a few URLs and their redirect status. I've spent quite some time looking for the best way to get the content of the HTTP response headers to retrieve the current code and redirect location. Here's how it's done at the moment:

$resource = fopen( $url, 'r' );
$metadata = stream_get_meta_data( $resource );
$metadata = $metadata['wrapper_data'];

// Looping through the array to find the necessary fields

      

This works for 95% of the urls that I control. I solved this a few more times by analyzing the actual HTML site that is being returned to the website before the redirect is done, as it contains something like "This site was moved here." It doesn't seem like a very robust solution, but it did help in a few cases.

This still leaves me with a few URLs that I cannot check automatically.

Tools like Ask Apache HTTP Headers Tool seem to be more reliable and I was wondering what might be the best way to get redirect information

+2


source to share


1 answer


You can also try curling, the shortest possible example that fetches all headers looks like this:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://stackoverflow.com');
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);

function read_header($ch, $string) {
    print "Received header: $string";
    return strlen($string);
}

      

Output:



[~]> php headers.php 
Received header: HTTP/1.1 200 OK
Received header: Cache-Control: private
Received header: Content-Type: text/html; charset=utf-8
Received header: Expires: Mon, 31 Aug 2009 09:38:45 GMT
Received header: Server: Microsoft-IIS/7.0
Received header: Date: Mon, 31 Aug 2009 09:38:45 GMT
Received header: Content-Length: 118666
Received header: 

      

Of course, these are just the headers you want, and fsockopen works just as well. Except, instead of GET, you should use HEAD, because you just want headers, not content.

Also curl works (if you compiled it with ssl support) for https url-s.

+6


source







All Articles