我正在向需要令牌身份验证的远程服务器(vebra api)发出curl
请求。据我所知,服务器每小时只允许一个令牌请求。我正在尝试识别我当前的令牌是否当前有效。
我的方法是提出请求并检查状态是200还是401。如果我有一个有效的令牌,我可以用curl_getinfo($ch)
成功地检查curl信息以获得正确的状态代码。如果我的令牌无效,但是脚本在我无法处理错误的情况下终止-在我可以处理错误或处理任何其他代码之前,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文档说的是不同的东西
关于php - 如何在CURL中处理服务器的连接重置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19892658/