正如其他人所建议的那样,听起来在单独的 php 进程中运行文件与您想要的很接近。但是您应该改用 proc_open() ,这样您就可以同时检查 stdout 和 stderr (这里的其他答案只允许您检查 STDOUT,这对检测错误没有多大帮助),如果发生错误,错误很可能是在 stderr 中打印(PHP 默认将错误打印到 stderr,而不是 stdout。)。在这篇文章的最后是一个自定义版本的 shell_exec,它允许您单独监控 stdout 和 stderr,如果您的脚本需要 stdin 数据,您可以将数据写入 stdin,您可以使用它测试单个脚本,如
$cmd=implode(" ",array(
"php",
escapeshellarg("path/to/my_new_file.php"),
// if your script needs extra arguments, add them here
));
$stdin=""; // if your script needs stdin data, add it here
$ret=my_shell_exec($cmd,$stdin,$stdout,$stderr);
之后,您的脚本放入 stderr 的任何内容现在都在 $stderr 变量中,并且它打印到 stdout 的任何内容都在 $stdout 变量中,检查它是否包含您所期望的。如果没有,您的脚本可能会以某种方式失败,$stderr/$stdout 的内容可能会告诉您如何它失败了。
function my_shell_exec(string $cmd, string $stdin=null, string &$stdout=null, string &$stderr=null):int{
//echo "executing \"{$cmd}\"...";
// use a tmpfile in case stdout is so large that the pipe gets full before we read it, which would result in a deadlock.
$stdout_handle=tmpfile();
$stderr_handle=tmpfile();
$descriptorspec = array(
0 => array("pipe", "rb"), // stdin is *inherited* by default, so even if $stdin is empty, we should create a stdin pipe just so we can close it.
1 => $stdout_handle,
2 => $stderr_handle,
);
$proc=proc_open($cmd,$descriptorspec,$pipes);
if(!$proc){
throw \RuntimeException("proc_exec failed!");
}
if(!is_null($stdin) && strlen($stdin)>0){
fwrite($pipes[0],$stdin);
}
fclose($pipes[0]);
$ret=proc_close($proc);
rewind($stdout_handle);// stream_get_contents can seek but it has let me down earlier, https://bugs.php.net/bug.php?id=76268
rewind($stderr_handle);//
$stdout=stream_get_contents($stdout_handle);
fclose($stdout_handle);
$stderr=stream_get_contents($stderr_handle);
fclose($stderr_handle);
//echo "done!\n";
return $ret;
}