[英]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.