我的php curl请求超时,因为我预期它并给我错误消息:“操作在120000毫秒后收到234570字节时超时”
但是,如果超时,我如何获得收到的字节?
$url = "example.com";
$timeout = 120;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$curl_page = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
var_dump($curl_page, $error);
答案 0 :(得分:1)
请勿使用CURLOPT_RETURNTRANSFER。请改用CURLOPT_FILE,例如
$outfileh=tmpfile();
$outfile=stream_get_meta_data($outfileh)['uri'];
curl_setopt($ch,CURLOPT_FILE,$outfileh);
curl_exec($ch);
$curl_page=file_get_contents($outfile);
(并且不要忘记fclose($ outfileh),否则你会有资源泄漏,请记住,使用tmpfile()' s,fclose()将删除文件也适合你......好消息是,php会在执行结束时将其清理干净) - 另一种选择是使用CURLOPT_WRITEFUNCTION,例如
$curl_page = '';
curl_setopt ( $ch, CURLOPT_WRITEFUNCTION, function ($ch, $recieved) use (&$curl_page) {
$curl_page .= $recieved;
return strlen ( $recieved );
} );
curl_exec($ch);