dtrvzd1171 2013-03-05 11:10
浏览 41
已采纳

来自unix命令的PHP CLI错误

I am writing php script, which will be used for making sites from "standart" site. There's a lot of unix shell commands, and I've found the problem with displaying errors.

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

  • 写回答

1条回答 默认 最新

  • dounue6984 2013-03-05 11:23
    关注

    You don't need the output from these CLI calls, just the error code. 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).

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大