【问题标题】:php exec with arguments still not working带有参数的php exec仍然无法正常工作
【发布时间】:2011-05-25 09:10:13
【问题描述】:

我花了几个小时试图完成这项工作,但没有成功。我在这个网站上搜索了关于如何在我的帖子中很好地显示代码的常见问题解答,但没有找到任何东西,请问有什么提示吗?

我有以下命令在 linux 服务器的命令行上运行良好,但是当我将它传递给 php exec 函数并通过 apache 在 linux 服务器上运行它时,它会显示脚本生成的使用信息被调用,而不是该脚本的输出。

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

我尝试过: 将整个命令字符串发送给 exec

通过 escapeshellcmd 将整个命令发送到 exec

将参数作为一个字符串(-arg1 "Arg1 value" -arg2 value2 -arg3 value3) 通过 escapeshellarg 发送到 exec

通过 escapeshellarg 将参数单独发送(例如:-arg1 "Arg1 value")到 exec

通过 escapeshellcmd 单独发送参数(例如:-arg1 "Arg1 value")到 exec

结果要么是没有输出,要么是被调用脚本的使用信息,说明参数没有正确传递。

代码如下:

$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_arguments, &$data);
print_r($data);

这是 apache 服务器上 php 脚本的输出:

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] => ) 

有人知道我错过了什么吗?

【问题讨论】:

  • 你能发布正确的代码吗? (例如,您的示例未用引号括起来)
  • 查看error.log 以发现执行错误(路径/权限)。

标签: php exec


【解决方案1】:

这里的问题是您正在转义开关以及值。您可以在输出中看到开关包含在一对单引号中,这意味着 myTool 程序中的 getopts 调用可能将 -arg1 "Arg1 Value" 解释为单个字符串参数,而不是带有字符串值的开关.

解决办法是只在值部分转义shellarg:

例如。

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

这应该实现你所追求的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多