我正在向需要令牌身份验证的远程服务器(Vebra Api)发出curl
请求。从我可以收集的内容来看,服务器每小时只允许一个令牌请求。我试图辨别我当前的令牌当前是否有效。
我的方法是发出请求并检查状态是200还是401.如果我有一个有效的令牌,我可以使用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);
答案 0 :(得分:0)
我认为简单地说$ curlResp是一个字符串
尝试使用
if ($curlResp == FALSE) {
die('yarrrghhh! :(');
//throw new Exception();
}
我已经测试了这段代码并通过php-cli和它上面的var_dump返回一个字符串..这很奇怪,因为php文档说不同的东西