解析用于与API交互的HTTP状态代码

tch*_*ore 2 php curl http-status-codes

我正在PHP中构建一个脚本来与API交互,并且需要能够解析API给我的HTTP状态代码.在大多数情况下,它提供以下响应之一:

HTTP/1.1 401 Unauthorized
HTTP/1.1 403 Forbidden 
HTTP/1.1 404 Not Found 
HTTP/1.1 410 Gone 
Run Code Online (Sandbox Code Playgroud)

我需要能够识别正在给出的响应,并且,如果它的401或410,继续,但是,如果它是401或403,在连续几次之后跟踪并关闭脚本(因为我超过了当天的通话限制.

我的代码非常简单:

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?
     }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我不知道在'else'循环中放什么.我正在使用CodeIgniter框架,如果有人知道任何使用的快捷方式.此外,我愿意使用cURL,但从未有过.

web*_*ave 5

这对正则表达式来说是一个很好的工作,因为状态总是以下列形式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
Run Code Online (Sandbox Code Playgroud)

的preg_match

$ http_response_header