开发者

php exec with arguments still not working

I have spent a few hours trying to make this work, but without success. I searched the FAQ on this site on how to nicely display code in my post but didn't find anything, any tips please?

I have the following command that works fine on the command line on a linux server, but when I pass it to the php exec function and run it through apache on a linux server it will show me the usage info produced by the script that is called, instead of the output from that script.

myTool -arg1 "Arg1 value" -arg2 value2 -arg3 value3

I have tried: sending that whole command string to exec

sending that whole command via escapeshellcmd to exec

sending the arguments all together as one string (-arg1 "Arg1 value" -arg2 value2 -arg3 value3) via escapeshellarg to exec

sending the arguments individually (for example: -arg1 "Arg1 value") via escapeshellarg to exec

sending the arguments individually (for example: -arg1 "Arg1 value") via escapeshellcmd to exec

The result is either no output or the usage info of the script that is called, suggesting that the arguments are not passed correctly.

Here is the code:

$data = array();
$commandexec = "/tools/myTool ";
$arg1 = "-arg1 \"Arg1 value\"";
$arg2 = "-arg2 value2";
$arg3 = "-arg3 value3";
$arguments_escaped = escapeshellarg($arg1). " ". escapeshellarg($arg2). " ".escapeshellarg($arg3);
$command_escaped_arguments = $commandexec . $arguments_escaped;
print "<br>command_escaped_arguments: ". $command_escaped_arguments ."<br>";
$result = exec($command_escaped_arg开发者_开发百科uments, &$data);
print_r($data);

this is the output of the php script on the apache server:

command_escaped_arguments: /tools/myTool '-arg1 "Arg1 value"' '-arg2 value2' '-arg3 value3'

Array ( [0] => 
[1] => myTool version 1.0 
[2] => Usage: myTool -arg1 "Some value" 
[3] => -arg3 option1|option2 
[4] => [-arg2 value] 
[5] => ) 

Anyone have an idea what I am missing?


The problem here is that you are escaping the switch as well as the value. You can see in the output that the switch is enclosed in a pair of single quotes, which means the getopts call in the myTool programme is probably interpreting -arg1 "Arg1 Value" as being a single string argument rather than a switch with a string value.

The solution is to escapeshellarg only on the value part:

eg.

$cmd = '/tools/myTool ' . '-arg1 ' . escapeshellarg("Arg1 Value") . ' -arg2 ' . escapeshellarg('Arg2 Value') etc etc...

That should achieve what you're after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜