[英]PHP CLI errors from unix commands
我正在编写php脚本,该脚本将用于从“标准”网站制作网站。 有很多unix shell命令,我发现了显示错误的问题。
示例:我需要检查站点文件夹还不存在。
$ls_newsite = exec('ls /vhosts/'.$sitename, $output, $error_code);
if ($error_code == 0) {
Shell::error('This site already exists in /vhosts/');
}
Shell::output(sprintf("%'.-37s",$sitename).'OK!');
因此,我可以处理错误,但是无论如何都会显示出来。
php shell.php testing.com
Checking site...
ls: cannot access /vhosts/testing.com: No such file or directory
testing.com.................................OK!
如何防止显示? 谢谢
您不需要这些CLI调用的输出,仅需要错误代码。 因此,将您的输出定向到/dev/null
(否则,PHP将打印stderr
到stderr
除非您使用proc_open
并为其中的每一个创建管道-过度proc_open
)。
$ls_newsite = exec('ls /vhosts/' . $sitename . ' > /dev/null 2>&1', $output, $error_code);
这将工作而无需任何输出。
现在,讨论其他一些问题:
将escapeshellarg
用于传递给shell命令的所有内容。 编写相同代码的更好方法是:
$ls_newsite = exec(sprintf('ls %s > /dev/null 2>&1', escapeshellarg('/vhosts/' . $sitename)), $output, $error_code);
100%确保需要使用控制台命令。 大多数基于文件的控制台命令( stat
, file_exists
, is_dir
等)都有PHP等效is_dir
,它们可以使您的代码更安全, 并使其与平台无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.