首页 >后端开发 >php教程 >如何从 PHP 中的 `exec()` 捕获标准错误输出?

如何从 PHP 中的 `exec()` 捕获标准错误输出?

Linda Hamilton
Linda Hamilton原创
2024-11-29 07:39:12506浏览

How Can I Capture Standard Error Output from `exec()` in PHP?

在 PHP 中的 Exec() 后检索标准错误流

问题:

你使用 PHP 的 exec() 函数重新执行命令并希望捕获写入标准错误的潜在错误消息

解决方案:

PHP 提供了一种更全面的方法来使用 proc_open 控制和捕获标准输出和错误流。

使用方法:

  1. 初始化输入/输出(I/O) 描述符规范,定义标准流的行为:
$descriptorspec = [
    0 => ["pipe", "r"],  // stdin
    1 => ["pipe", "w"],  // stdout
    2 => ["pipe", "w"],  // stderr
];
  1. 使用 proc_open 执行命令并提供描述符规范:
$process = proc_open($command, $descriptorspec, $pipes, dirname(__FILE__), null);
  1. 使用从标准错误管道读取Stream_get_contents:
$stderr = stream_get_contents($pipes[2]);

示例:

考虑以下脚本 test.sh:

#!/bin/bash

echo 'this is on stdout';
echo 'this is on stdout too';

echo 'this is on stderr' >&2;
echo 'this is on stderr too' >&2;

在 PHP 脚本中,我们可以运行 test.sh 并捕获 stdout 和stderr:

$descriptorspec = [0 => ["pipe", "r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]];
$process = proc_open('./test.sh', $descriptorspec, $pipes);

$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);

echo "stdout: $stdout";
echo "stderr: $stderr";

输出:

stdout: this is on stdout
this is on stdout too

stderr: this is on stderr
this is on stderr too

以上是如何从 PHP 中的 `exec()` 捕获标准错误输出?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn