Search code examples
phpshell-execmailx

PHP shell_exec failed due to some specific character


I'm using shell_exec function to call mailx command on Ubuntu to send mail, but received error as there is specific character in the command, please see my below code and result.

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

echo "StringA:", $stringA, "<br/>";
$res = shell_exec("echo $stringA | mailx -s 'testA' [email protected]");
echo $res, "<br/>";

echo "StringB:", $stringB, "<br/>";
$res = shell_exec("echo $stringB | mailx -s 'testB' [email protected]");
echo $res, "<br/>";

When I call this page on the server, I got below page:

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

and I received the mail with content Visit STAR WARS, and cannot received the mail with content Visit STAR WARS™.

I checked from the phpinfo function, and the default_charset is "utf-8". if i run the command "echo Visit STAR WARS™ | mailx -s 'testB' [email protected]"directly on the Ubuntu shell, I can get the mail with **™**content.

Can anyone help me to fix the problem so that shell_exec function can send mail with specific characters.


Solution

  • $ [dollar sign] has a special meaning in shell scripts , so you can not pass it within the command ,

    $res = shell_exec("echo '" . $stringA . "' | mailx -s 'testA' [email protected]");
    

    and it's always better to use escapeshellarg to escape your arguments as follows :

    $res = shell_exec("echo '" . escapeshellarg($stringA) . "' | mailx -s 'testA' [email protected]");