views:

29

answers:

2

I'm building a script in PHP to interact with an API and need to be able to parse the HTTP status code the API is giving me. For the most part, it gives one of the following responses:

HTTP/1.1 401 Unauthorized
HTTP/1.1 403 Forbidden 
HTTP/1.1 404 Not Found 
HTTP/1.1 410 Gone 

I need to be able to recognize which response is being given, and, if its 401 or 410, to keep going, but, if it's 401 or 403, to keep track and to shut down the script after a few in a row (because I've exceeded my call limit for the day).

My code is pretty simple:

for($i = $start;$i < $end;$i++)
{
     // construct the API url
     $url = $base_url.$i.$end_url;
     // make sure that the file is accessible
     if($info = json_decode(file_get_contents($url)))
     {
        // process retrieved data
     } else {
        // what do I put here?
     }
}

My problem is I don't know what to put in the 'else' loop. I'm using the CodeIgniter framework, if anyone knows of any shortcuts to use. Also, I'm open to using cURL, but never have before.

+2  A: 

This is a good job for regex as statuses are always in the form of version code text:

$matches = array();
preg_match('#HTTP/\d+\.\d+ (\d+)#', $http_response_header[0], $matches);
echo $matches[1]; // HTTP/1.1 410 Gone return 410

preg_match

$http_response_header

webbiedave
You first need to get the status string. I don't think this anwser the question. [edit] Ok you added the `$http_response_header`, I now feel robbed.
Savageman
I was adding it Savageman :) I think it was implicit in his question how to parse the code from the status header as well.
webbiedave
lol. Sorry Savageman but I added that before I saw your answer. You can check revision history and you'll see it in there. Don't feel robbed. Happens to me all the time. I'm upvoting yours as well.
webbiedave
No worries. No harm done. ^^
Savageman
+2  A: 

This is what you need: http://php.net/manual/en/reserved.variables.httpresponseheader.php

Savageman