php - 使 cURL 输出 STDERR 到文件(或字符串)

标签 php curl stderr verbose

我们正在尝试调试服务器上的一些 cURL 错误,我想查看 STDERR 日志。目前,我们只能看到错误“错误代码:7”,并且无法连接到目标服务器。我们已经联系了主机并制定了特殊规则来打开我们需要的端口,我们甚至暂时忽略了证书。

我们仍然无法连接。我需要对此进行调试,但我看不到任何相关信息。

我认为提到“VERBOSE”和“STDERR”的行是最重要的。 $curl_log 中未写入任何内容。我究竟做错了什么?按照手册的逻辑,这应该是正确的......

使用 PHP:

<?php
$curl = curl_init();
$curl_log = fopen("curl.txt", 'w');
$url = "http://www.google.com";

curl_setopt_array($curl, array(
    CURLOPT_URL             => $url,        // Our destination URL
    CURLOPT_VERBOSE         => 1,           // Logs verbose output to STDERR
    CURLOPT_STDERR          => $curl_log,   // Output STDERR log to file
    CURLOPT_SSL_VERIFYPEER  => 0,           // Do not verify certificate
    CURLOPT_FAILONERROR     => 0,           // true to fail silently for http requests > 400
    CURLOPT_RETURNTRANSFER  => 1            // Return data received from server
));

$output = fread($curl_log, 2048);
echo $output; // This returns nothing!
fclose($curl_log);

$response = curl_exec($curl);
//...restofscript...
?>

来自 PHP 手册:http://php.net/manual/en/function.curl-setopt.php

CURLOPT_VERBOSE TRUE to output verbose information. Writes output to STDERR CURLOPT_STDERR An alternative location to output errors to instead of STDERR.

这也不是权限问题,我在服务器端将文件和脚本权限设置为777,而我的本地客户端是Windows,从来不关心权限设置(反正只针对开发人员)。

最佳答案

您在示例中犯了几个错误:

1) 在读取“详细日志”之前,您必须调用 curl_exec(),因为 curl_setopt() 不会执行任何操作,因此在curl_exec()之前不会记录任何内容。

2) 您正在打开 $curl_log = fopen("curl.txt", 'w'); 仅用于写入,因此即使在之后也无法读取任何内容您写入文件并倒回内部文件指针。

所以正确的缩短代码应该如下所示:

<?php
$curl = curl_init();
$curl_log = fopen("curl.txt", 'rw'); // open file for READ and write
$url = "http://www.google.com";

curl_setopt_array($curl, array(
    CURLOPT_URL             => $url,
    CURLOPT_VERBOSE         => 1,
    CURLOPT_STDERR          => $curl_log,
    CURLOPT_RETURNTRANSFER  => 1
));

$response = curl_exec($curl);

rewind($curl_log);
$output= fread($curl_log, 2048);
echo "<pre>". print_r($output, 1). "</pre>";
fclose($curl_log);

// ...

?>

注意:详细日志可能超过 2048 字节,因此您可以在curl_exec()之后“fclose”$curl_log,然后使用例如file_get_contents()读取整个文件。 在这种情况下,2) 点不应被视为错误:-)

关于php - 使 cURL 输出 STDERR 到文件(或字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868808/

相关文章:

php - 有没有适合初学者的 Solr 教程?

Php MySQL - 按限制删除所有行

javascript - 用于 php 脚本的 AJAX

tomcat - 通过 CURL 终止 Tomcat 中的 session

PHP Curl 和 Cookie

c - 如何在 c 中使用 execl() 函数在文件中打印 stderr 消息

python - 使用python的子进程模块打开一个python进程

php - sendmail.exe 在发送邮件时打开

linux - Bash 脚本 - 将子脚本 stderr 重定向到父脚本的 stdout

r - 安装包 ‘devtools’ 在 Ubuntu 上具有非零退出状态