Answers:
您可以启用该CURLOPT_VERBOSE
选项并将该信息记录到(临时)CURLOPT_STDERR
:
// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR,
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);
您可以在curl完成请求后阅读它:
$result = curl_exec($handle);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
htmlspecialchars(curl_error($handle)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
有关更多信息,例如有关上次请求的指标,可通过访问curl_getinfo
。该信息对于调试curl请求也很有用。一个使用示例,我通常将其包装为一个函数:
$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;
这是相同的简单代码:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fp);
其中$ fp是输出错误的文件句柄。例如:
$fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');
如果您只想快速调试结果:
$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"
另一个(粗略的)选择是利用netcat转储完整的请求:
nc -l -p 8000 -w 3 | tee curldbg.txt
当然向它发送失败的请求:
curl_setup(CURLOPT_URL, "http://localhost/testytest");
值得注意的是,由于netcat永远不会构造有效的HTTP响应,因此始终会挂起+失败。它实际上只是用于检查实际发送的内容。当然,更好的选择是使用http请求调试服务。
将调试信息输出到STDERR:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option
*/
CURLOPT_VERBOSE => true,
]);
curl_exec($curlHandler);
curl_close($curlHandler);
输出调试信息到文件:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/get?foo=bar',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify debug option.
*/
CURLOPT_VERBOSE => true,
/**
* Specify log file.
* Make sure that the folder is writable.
*/
CURLOPT_STDERR => fopen('./curl.log', 'w+'),
]);
curl_exec($curlHandler);
curl_close($curlHandler);
参见https://github.com/andriichuk/php-curl-cookbook#debug-request