简体   繁体   中英

PHP: cannot run nested shell scripts

I hope you can help me.

I am dealing with a problem that I cannot solve. This is my issue. I am trying to exec a bash script through PHP. I tried with the method

exec()

with 3 arguments, arg1, arg2, and arg3.

php code

<?php exec("./randomScript.sh arg1 arg2 arg3"); ?>

randomScript.sh

.... # random code which exploits the three arguments -> executed normally..
.... # random code which exploits the three arguments -> executed normally..

./secondScript.sh $arg1 $arg2 $arg3 #<- this is the script that is not running (is not even started).

I have tried to change the permission (I've got full permission), change the way I call the randomScript.sh (through absolute path), but nothing occurred. Besides, I tried with:

shell_exec()

method, but nothing changed. Of course, if I run the secondScript.sh via terminal everything works fine.

I cannot understand which is the problem. Could you please help me?

Thanks in advance.

You should escape your string command before passing it in exec function, i think it may help you Escapeshellcmd()

...
$escaped_command = escapeshellcmd("./randomScript.sh arg1 arg2 arg3");
exec($escaped_command);
...

Escapeshellarg()

For system command, i recommand using system

...
$escaped_command = escapeshellarg("./randomScript.sh arg1 arg2 arg3");
system($escaped_command);
...

In the inner shell, the arguments are not called like that (because it is invoked by the shell, not by PHP).

./secondScript.sh "$1" "$2" "$3"

or just

./secondScript.sh $*

At this stage, just remember that spaces, quotes, and dollar signs in the arguments you pass must be avoided at all costs (the solution is escaping them, but how to do it exactly is tricky).

You also might want to do instead:

$ret = shell_exec("./randomScript.sh 'arg1' 'arg2' 'arg3' 2>&1");

so that in $ret you might find error messages and output from the inner shell.

You also need to make sure that your PHP code does not change working dir, and both shell scripts have execute permissions, and filesystems allows to exec files on it.

I would avoid exec("./script $arg ..."); , I would rather specify the interpreter to use and full path to the script like exec("sh /home/user/project/script.sh $arg ...");

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