如何从 PHP 命令行捕获 stderr

Sha*_*mar 3 php c compiler-construction

我想创建一个 C/C++ 在线编译器。

到目前为止我已经开发了以下代码:

<?php
error_reporting(E_ALL);
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{


    move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
    compile();
}
function compile()
{
$a=shell_exec('gcc -o Compile Compile.c');
echo $a;
$b=shell_exec('./Compile');
echo $b;
}
?>
Run Code Online (Sandbox Code Playgroud)

文件 Compile.c 正在上传,然后由 gcc 编译。我想做的是:

  • 当编译出错时从stderr读取错误并显示在网页上。
  • 如果没有错误,则在输入文件上执行代码并显示执行时间,如果时间超过特定值,则显示超出时间限制的错误。

我在网上搜索发现如果编译语句附加“2>&1”作为

$a=shell_exec('gcc -o Compile Compile.c 2>&1');
Run Code Online (Sandbox Code Playgroud)

然后编译错误的输出返回到分配的变量(上面例子中的$a),但不是没有它。所以我的问题是如何检查错误然后将其显示在网页上而不附加“2>&1”,如果没有错误,则执行上面给出的第二步。

Tho*_*hem 6

proc_open() 的正确使用如下所示:

$process = proc_open('gcc -o Compile Compile.c', array(
    0 => array('pipe', 'r'), // STDIN
    1 => array('pipe', 'w'), // STDOUT
    2 => array('pipe', 'w')  // STDERR
), $pipes);

if(is_resource($process)) {
    // If you want to write to STDIN
    fwrite($pipes[0], '...');
    fclose($pipes[0]);

    $stdOut = stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    $stdErr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);

    $returnCode = proc_close($process);
}
Run Code Online (Sandbox Code Playgroud)

这将执行 shell 命令并为您提供 STDIN、STDOUT 和 STDERR 的详细控制。