Passing multiple PHP variables to shell_exec()?

不想你离开。 提交于 2019-11-26 11:08:31

问题


I am calling test.sh from PHP using shell_exec method.

$my_url=\"http://www.somesite.com/\";
$my_refer=\"http://www.somesite.com/\";
$page = shell_exec(\'/tmp/my_script.php $my_url $my_refer\');

However, the command line script says it only received 1 argument: the /tmp/my_script.php

When i change the call to:

Code:

$page = shell_exec(\'/tmp/my_script.php {$my_url} {$my_refer}\');

It says it received 3 arguments but the argv[1] and argv[2] are empty.

When i change the call to:

Code:

$page = shell_exec(\'/tmp/my_script.php \"http://www.somesite.com/\" \"http://www.somesite.com/\"\');

The script finally receives all 3 arguments as intended.

Do you always have to send just quoted text with the script and are not allowed to send a variable like $var? Or is there some special way you have to send a $var?


回答1:


There is need to send the arguments with quota so you should use it like:

$page = shell_exec("/tmp/my_script.php '".$my_url."' '".$my_refer."'");



回答2:


Change

$page = shell_exec('/tmp/my_script.php $my_url $my_refer');

to

$page = shell_exec("/tmp/my_script.php $my_url $my_refer");

OR

$page = shell_exec('/tmp/my_script.php "'.$my_url.'" "'.$my_refer.'"');

Also make sure to use escapeshellarg on both your values.

Example:

$my_url=escapeshellarg($my_url);
$my_refer=escapeshellarg($my_refer);



回答3:


Variables won't interpolate inside of a single quoted string. Also you should make sure the your arguments are properly escaped.

 $page = shell_exec('/tmp/myscript.php '.escapeshellarg($my_url).' '.escapeshellarg($my_refer));



回答4:


Change

$page = shell_exec('/tmp/my_script.php $my_url $my_refer');

to

$page = shell_exec('/tmp/my_script.php "'.$my_url.'" "'.$my_refer.'"');

Then you code will tolerate spaces in filename.




回答5:


You might find sprintf helpful here:

$my_url="http://www.somesite.com/";
$my_refer="http://www.somesite.com/";
$page = shell_exec(sprintf('/tmp/my_script.php "%s" "%s"', $my_url, $my_refer));

You should definitely use escapeshellarg as recommended in the other answers if you're not the one supplying the input.




回答6:


I had difficulty with this so thought I'd share my code snippet.

Before

$output = shell_exec("/var/www/sites/blah/html/blahscript.sh 2>&1 $host $command");

After

$output = shell_exec("/var/www/sites/blah/html/blahscript.sh 2>&1 $host {$command}");

Adding the {} brackets is what fixed it for me.

Also, to confirm escapeshellarg is also needed.

$host=escapeshellarg($host);
$command=escapeshellarg($command);

Except script also needed:

set host [lindex $argv 0]
set command [lindex $argv 1]


来源:https://stackoverflow.com/questions/16932113/passing-multiple-php-variables-to-shell-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!