如何在 CURL 中处理服务器重置的连接


How to handle connection reset by server in CURL

我正在向需要令牌身份验证的远程服务器(Vebra Api)发出curl请求。据我所知,服务器每小时只允许一个令牌请求。我正在尝试辨别我当前的令牌当前是否有效。

我的方法是提出请求并检查状态是 200 还是 401。如果我有一个有效的令牌,我可以成功地检查 curl 信息与 curl_getinfo($ch) 的正确状态代码。但是,如果我的令牌无效,脚本会在我无法处理错误的情况下终止 - Firefox 会在我处理错误或处理任何其他代码之前报告该The connection was reset

这是我的代码还是服务器的问题?在这种情况下,是否有办法告诉 curl 函数调用某个函数?

代码如下:

// an invalid token
$token = '1sdfsdfds1RQUlJTTU1GRVdVT0tYUkJsdfsdfsdfdsfsdSEg=';
//Initiate a new curl session
$ch = curl_init($url);
//Don't require header this time as curl_getinfo will tell us if we get HTTP 200 or 401
curl_setopt($ch, CURLOPT_HEADER, 0); 
//Provide Token in header
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic '. $token ) ); 
// Tell curl to return a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the curl session
$curlResp = curl_exec($ch);
// -----------------------------------------------------------------------------
// with invalid token script ends here with no chance for me to handle the error
// such as below
// -----------------------------------------------------------------------------
if ($curlResp === FALSE) {
    die('yarrrghhh! :(');
    //throw new Exception(); 
}
//Store the curl session info/returned headers into the $info array
$info = curl_getinfo($ch);
//Check if we have been authorised or not
if($info['http_code'] == '401') {
    echo 'Token Failed';
    var_dump($info);
    var_dump($curlResp);
} 
elseif ($info['http_code'] == '200') {
    echo 'Token Worked';
    var_dump($info);
    var_dump($curlResp);
}
//Close the curl session
curl_close($ch);

我认为简单地$curlResp是一个字符串

尝试使用

if ($curlResp == FALSE) {
die('yarrrghhh! :(');
//throw new Exception(); 
}

我已经测试了这段代码,并通过 php-cli 和它上面的var_dump返回一个字符串.. 这很奇怪,因为 PHP 文档说了不同的事情