views:

330

answers:

3

I am using the following PHP:

$xml = simplexml_load_file($request_url) or die("url not loading");

I use:

$status = $xml->Response->Status->code;

To check the status of the response. 200 bening everything is ok, carry on.

However if I get a 403 access denied error, how do I catch this in PHP so I can return a user friendly warning?

A: 

You'll have to use something like the cURL module or the HTTP module to fetch the file, then use the functionality provided by them to detect an HTTP error, then pass the string from them into simplexml_load_string.

pib
+2  A: 

To retrieve the HTTP response code from a call to simplexml_load_file(), the only way I know is to use PHP's little known $http_response_header. This variable is automagically created as an array containing each response header separately, everytime you make a HTTP request through the HTTP wrapper. In other words, everytime you use simplexml_load_file() or file_get_contents() with a URL that starts with "http://"

You can inspect its content with a print_r() such as

$xml = @simplexml_load_file($request_url);
print_r($http_response_header);

In your case, though, you might want to retrieve the XML separately with file_get_contents() then, test whether you got a 4xx response, then if not, pass the body to simplexml_load_string(). For instance:

$response = @file_get_contents($request_url);
if (preg_match('#^HTTP/... 4..#', $http_response_header[0]))
{
    // received a 4xx response
}

$xml = simplexml_load_string($response);
Josh Davis
I should have been a little more clear - although this works and allows me to catch the error and stop the script from trying to do anything more. I still get the default warning message: Warning: file_get_contents(http://domain.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 ForbiddenThe reason for catching them is I am making several requests and want to cleanly catch the error when it happens and give a user friendly warning rather than the default.
Scoobler
Then you use the mute operator @ as demonstrated in the updated snippet. http://docs.php.net/manual/en/language.operators.errorcontrol.php
Josh Davis
A: 

Thank you Thank you Thank you Thank you Thank you Thank you Thank you

Anoop