将多个PHP变量传递给shell_exec()?

时间:2013-06-05 05:22:35

标签: php shell shell-exec

我使用shell_exec方法从PHP调用test.sh。

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

但是,命令行脚本说它只收到1个参数:/tmp/my_script.php

当我将通话更改为:

代码:

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

它说它收到了3个参数,但是argv [1]和argv [2]是空的。

当我将通话更改为:

代码:

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

脚本最终按预期接收所有3个参数。

您是否始终只需使用脚本发送带引号的文本,并且不允许发送像$ var这样的变量?或者是否有一些特殊方式你必须发送$ var?

6 个答案:

答案 0 :(得分:19)

更改

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

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

OR

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

另外,请务必在两个值上使用escapeshellarg

示例:

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

答案 1 :(得分:13)

需要发送带有配额的参数,因此您应该使用它:

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

答案 2 :(得分:8)

变量不会在单个带引号的字符串内插。此外,您应确保正确转义您的参数。

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

答案 3 :(得分:2)

更改

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

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

然后你的代码将容忍文件名中的空格。

答案 4 :(得分:2)

您可能会在此处找到sprintf

$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));

如果您不是提供输入的人,请务必使用其他答案中建议的escapeshellarg

答案 5 :(得分:2)

我遇到了这个问题,以为我会分享我的代码片段。

<强>之前

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

之后

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

添加{}括号是我修复它的原因。

此外,还需要确认escapeshellarg

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

除了脚本还需要:

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