[英]PHP CLI errors from unix commands
I am writing php script, which will be used for making sites from "standart" site. 我正在编写php脚本,该脚本将用于从“标准”网站制作网站。 There's a lot of unix shell commands, and I've found the problem with displaying errors. 有很多unix shell命令,我发现了显示错误的问题。
Example: I need to check that the site folder doesn't exist yet. 示例:我需要检查站点文件夹还不存在。
$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!');
So, I can handle error, but it will be display anyway. 因此,我可以处理错误,但是无论如何都会显示出来。
php shell.php testing.com
Checking site...
ls: cannot access /vhosts/testing.com: No such file or directory
testing.com.................................OK!
How can I prevent displaying? 如何防止显示? Thanks 谢谢
You don't need the output from these CLI calls, just the error code. 您不需要这些CLI调用的输出,仅需要错误代码。 So direct your output to /dev/null
(otherwise PHP will print whatever goes to stderr
unless you use proc_open
and create pipes for each of these - overkill). 因此,将您的输出定向到/dev/null
(否则,PHP将打印stderr
到stderr
除非您使用proc_open
并为其中的每一个创建管道-过度proc_open
)。
$ls_newsite = exec('ls /vhosts/' . $sitename . ' > /dev/null 2>&1', $output, $error_code);
That will work without giving you any output. 这将工作而无需任何输出。
Now, on to a few other issues: 现在,讨论其他一些问题:
Use escapeshellarg
for anything you're passing to a shell command. 将escapeshellarg
用于传递给shell命令的所有内容。 A better way to write this same code is: 编写相同代码的更好方法是:
$ls_newsite = exec(sprintf('ls %s > /dev/null 2>&1', escapeshellarg('/vhosts/' . $sitename)), $output, $error_code);
Be 100% sure that you need to use console commands. 100%确保需要使用控制台命令。 There are PHP equivalents for most file-based console commands ( stat
, file_exists
, is_dir
, etc) that would make your code both more secure and would allow it to be platform-independent. 大多数基于文件的控制台命令( stat
, file_exists
, is_dir
等)都有PHP等效is_dir
,它们可以使您的代码更安全, 并使其与平台无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.