【问题标题】:Error retrieving exec() output检索 exec() 输出时出错
【发布时间】:2012-07-22 11:03:50
【问题描述】:

我正在使用 exec 来获取 curl 输出(我需要使用 curl 作为 linux 命令)。

当我使用 php_cli 启动文件时,我看到一个 curl 输出:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 75480  100 75480    0     0  55411      0  0:00:01  0:00:01 --:--:-- 60432

这意味着所有文件都已正确下载(~ 75 KB)。

我有这个代码:

$page = exec('curl http://www.example.com/test.html');

我得到一个非常奇怪的输出,我只得到:</html>

(这是我的 test.html 文件的结尾)

我真的不明白原因,CURL似乎下载了所有文件,但在$page中我只得到7个字符(最后7个字符)。

为什么?

附:我知道我可以使用其他 php 函数下载源代码,但我必须使用 curl(作为 linux 命令)。

【问题讨论】:

标签: php linux curl


【解决方案1】:

除非这是一个非常奇怪的要求,否则为什么不使用 PHP cURL 库呢?您可以更好地控制发生的事情以及调用参数(超时等)。

如果你真的必须使用 PHP 中的 curl 命令行二进制文件:

1) Use shell_exec() (this solves your problem)
2) Use 2>&1 at end of command (you might need stderr output as well as stdout)
3) Use the full path to curl utility: do not rely on PATH setting.

【讨论】:

  • 在 PHP 不支持 curl 的环境中,有时您可能需要使用 curl 执行某些操作,因此外部执行回退仍然很有用。
【解决方案2】:

RTM for exec()

返回

命令结果的最后一行。

您必须将第二个参数设置为exec(),它将包含执行命令的所有输出。

例子:

<?php
$allOutputLines = array();
$returnCode = 0;
$lastOutputLine = exec(
    'curl http://www.example.com/test.html',
    $allOutputLines,
    $returnCode
);

echo 'The command was executed and with return code: ' . $returnCode . "\n";
echo 'The last line outputted by the command was: ' . $lastOutputLine . "\n";
echo 'The full command output was: ' . "\n";
echo implode("\n", $allOutputLines) . "\n";

?>

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2017-02-05
    相关资源
    最近更新 更多