【问题标题】:PHP passing string with apostrophe to shell_execPHP将带撇号的字符串传递给shell_exec
【发布时间】:2015-01-31 01:40:38
【问题描述】:

我正在尝试通过 PHP shell_exec 将字符串(从 PDO 查询中提取到 MYSQL DB)传递给 *nix 程序,在本例中为 xtide

在我传递一个包含撇号的字符串之前,一切正常。

这适用于 OSX 的终端:

house@New-MacBook-Pro:~$ tide -l "Nomans Land, Martha's Vineyard, Massachusetts"

但是完全相同的字符串,从 PDO 查询到 MYSQL DB,并作为变量传递给 shell_exec,总是失败。我如何排列单引号/双引号似乎并不重要。

运行它会添加反斜杠,但仍然失败:

$tideLocation = mysql_real_escape_string($tideLocation);

输出:

Nomans Land, Martha\’s Vineyard, Massachusetts

失败:

$output1 = shell_exec("/opt/local/bin/tide -l 'Nomans Land, Martha's Vineyard, Massachusetts'");

$output1 = shell_exec("/opt/local/bin/tide -l '$tideLocation'");

当在shell_exec 中手动设置时,此方法有效:

$output1 = shell_exec("/opt/local/bin/tide -l 'Nomans Land, Martha\'s Vineyard, Massachusetts'");

欢迎提出建议。

【问题讨论】:

    标签: php exec shell-exec


    【解决方案1】:

    使用escapeshellarg 为命令行参数正确转义单引号中的字符串。

    示例:

    $command = '/opt/local/bin/tide -l ' . escapeshellarg($tideLocation);
    shell_exec($command);
    

    【讨论】:

    • 太棒了,我完全错过了 escapeshellarg。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多