Hi Is there a way of retrieving HTTP error codes (404, 401, ...) when opening an url with fopen()? This function seems to either return a handle (success) or just false (failure). Cheers!
<?php $url = 'use your URL here'; $fp = fopen($url, 'r'); // The variable $http_response_header is now automagically populated print_r($http_response_header); ?> PHP: Enjoy! Bobby
Thanks a lot Chemo, exactly what I was looking for! For anyone interested, the full array of $http_response_header looks something like: [0] => HTTP/1.1 401 Authorization Required [1] => Date: Sun, 11 Jun 2006 17:18:33 GMT [2] => Server: Apache/1.3.29 (Unix) PHP/4.4.0 [3] => WWW-Authenticate: Basic realm="Members" [4] => Connection: close [5] => Content-Type: text/html; charset=iso-8859-1 Code (markup): To check the returned HTTP (error) code, do something like: if (strpos($http_response_header[0], '404') !== false) echo "Error: Document not found."; PHP:
You could expand that and use something like this: $return_code = @explode(' ', $http_response_header[0]); $return_code = (int)$return_code[1]; switch($return_code){ case 301: // do something break; case 302: // do something break; case 404: // do something break; default: // do something break; } PHP: Bobby
Looks like an elegant solution Is the return code always of the format "HTTPsomething Number Message"?
Yes...if it is a 301 or 302 there will be an additional element in the array of the form Location: domain.com/new_url.php. I have that in my switch statement to check the number of redirects and also present the final URL.
Huh this doesn't work for me eg $content = file_get_contents($url); var_dump($http_response_header); //issues a notice $http_response_header not defined //while this one works fine var_dump(get_headers($url) ); PHP: this is on PHP 5.1.4 MacOSX