来自unix命令的PHP CLI错误

问题描述:

我正在写php脚本,它将用于从“standart”站点制作站点。 有很多unix shell命令,我发现显示错误的问题。来自unix命令的PHP CLI错误

示例:我需要检查站点文件夹是否还不存在。

$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! 

如何防止显示?谢谢

+0

正如@Colin Morelli所说,你不需要为此使用控制台命令。 'file_exists'就足够了。 – andy 2013-03-05 11:26:09

+0

这只是显示问题的例子。 – Kirill 2013-03-05 11:55:12

+0

但即便如此,并不是很多情况下你应该使用'exec'命令。 – andy 2013-03-05 11:56:42

您不需要这些CLI调用的输出,只是错误代码。所以直接输出到/dev/null(否则PHP将打印任何去stderr,除非你使用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等价物,这会使您的代码更加安全将允许它与平台无关。