PHP将带撇号的字符串传递给shell_exec [英] PHP passing string with apostrophe to shell_exec

查看:71
本文介绍了PHP将带撇号的字符串传递给shell_exec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过PHP shell_exec将字符串(从PDO查询绘制到MYSQL DB)传递给* nix程序,在这种情况下为

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.

这在OSX的终端机上有效:

This works in the Terminal on OSX:

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

,但是从PDO查询到MYSQL DB并作为变量传递到shell_exec的完全相同的字符串始终会失败.我如何安排单引号/双引号似乎无关紧要.

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);

输出:

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中手动设置时,此方法有效:

This works, when set up manually in shell_exec:

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

最欢迎通知.

推荐答案

使用 escapeshellarg 正确地将命令行参数的单引号引起来的字符串转义.

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

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

这篇关于PHP将带撇号的字符串传递给shell_exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆