简体   繁体   中英

PHP CLI errors from unix commands

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM