我正在尝试通过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);