我正在尝试通过 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'");
欢迎提出建议。
最佳答案
使用escapeshellarg
正确转义命令行参数的单引号中的字符串。
示例:
$command = '/opt/local/bin/tide -l ' . escapeshellarg($tideLocation);
shell_exec($command);
关于PHP 将带撇号的字符串传递给 shell_exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28247280/