PHP passing string with apostrophe to shell_exec

穿精又带淫゛_ 提交于 2020-06-08 19:59:18

问题


I’m trying to pass a string (drawn from a PDO query to an MYSQL DB) via PHP shell_exec to a *nix program, in this case xtide.

All works fine until I pass a string containing an apostrophe.

This works in the Terminal on OSX:

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

but the exact same string, from a PDO query to a MYSQL DB, and passed as a variable into shell_exec, always fails. It doesn’t seem to matter how I arrange the single/double quotes.

Running this adds the backslash, but it still fails:

$tideLocation = mysql_real_escape_string($tideLocation);

outputs:

Nomans Land, Martha\’s Vineyard, Massachusetts

Failures:

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

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

This works, when set up manually in shell_exec:

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

Advice most welcome.


回答1:


Use escapeshellarg to properly escape a string in single quotes for a command line arguments.

Example:

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


来源:https://stackoverflow.com/questions/28247280/php-passing-string-with-apostrophe-to-shell-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!