PHP shell_exec 由于某些特定字符而失败

PHP shell_exec failed due to some specific character

我正在使用 shell_exec 函数调用 Ubuntu 上的 mailx 命令来发送邮件,但是由于命令中有特定字符而收到错误,请看我下面的代码和结果。

<?php
$stringA="Visit STAR WARS™";
$stringB="Visit STAR WARS";

echo "StringA:", $stringA, "<br/>";
$res = shell_exec("echo $stringA | mailx -s 'testA' my_email_address@mail.com");
echo $res, "<br/>";

echo "StringB:", $stringB, "<br/>";
$res = shell_exec("echo $stringB | mailx -s 'testB' my_email_address@mail.com");
echo $res, "<br/>";

当我在服务器上调用此页面时,我得到以下页面:

StringA: Visit STAR WARS™
"/var/www/dead.letter" 1/19 
StringB: Visit STAR WARS

收到内容为Visit STAR WARS的邮件,收不到内容为Visit STAR WARS™的邮件。

我从 phpinfo 函数中查看, default_charset 是 "utf-8"。 如果我 运行 命令 "echo Visit STAR WARS™ | mailx -s 'testB' my_email_address@mail.com" 直接在 Ubuntu shell 上,我可以收到带有 **™** 内容的邮件。

谁能帮我解决这个问题,让 shell_exec 函数可以发送特定字符的邮件。

$ [美元符号]在shell脚本中有特殊含义,所以你不能在命令中传递它,

$res = shell_exec("echo '" . $stringA . "' | mailx -s 'testA' my_email_address@mail.com");

最好使用 escapeshellarg 来转义您的参数,如下所示:

$res = shell_exec("echo '" . escapeshellarg($stringA) . "' | mailx -s 'testA' my_email_address@mail.com");