用 PHP 执行 linux 命令

2022-01-04 00:00:00 shell php scripting

我正在尝试通过 PHP 命令行脚本执行 linux 命令,使用 exec 命令没有问题.

I'm trying to execute a linux command through a PHP command-line script, which is no problem using the exec command.

问题是,如果出现错误(例如用户/密码不正确),我正在执行的命令 (mysqldump) 会输出错误消息.我似乎无法捕获此错误以记录它.它只是将这个错误打印到屏幕上.

The problem is, the command I am executing (mysqldump) outputs an error message if something is wrong (for example user/password is incorrect). I can't seem to be able to capture this error in order to log it. It just prints this error to the screen.

如何使此错误不打印到屏幕上,而是将其放入一个变量中以便在我的脚本中使用?

How do I cause this error not to be printed to the screen, but instead to put it in a variable for use in my script?

谢谢!

推荐答案

使用 popen 来运行流程.此页面上的示例 #2 准确显示了您要查找的内容:

Use popen to run the process. The example #2 on this page shows exactly what you're looking for:

<?php
error_reporting(E_ALL);

/* Add redirection so we can get stderr. */
$handle = popen('/path/to/spooge 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "
";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

相关文章