检索exec()输出时出错

时间:2012-07-22 11:03:51

标签: php linux curl

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

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

  % 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个字符)。

为什么?

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

2 个答案:

答案 0 :(得分:3)

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";

?>

答案 1 :(得分:3)

除非这是一个非常奇怪的要求,为什么不使用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.