开发者

Parsing HTTP status codes for interacting with API

开发者 https://www.devze.com 2023-01-19 18:22 出处:网络
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:

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 开发者_StackOverflow
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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消