Escaping Shell echos
I tried to do my research, there is just an abundance of ways to call shell commands, and even more ways to strip harmful characters that I am coming to stackoverflow for an expert's best recommendation.
I was hoping to find something like I've seen other languages so where sending arguments to a command are actually passed through a function, like:
do_command("ls", "-l", $Directory);
and it will take care of anything harmful in the $Directory variable for you. I haven't quite found this with PHP.
This is the code I am working with:
<?php
session_start();
$AdminEmail = "random_email@gmail.com";
$CatalogEmails = array("");
$QuoteEmails = array("");
$PartsEmails = array("");
$Subject = $_SESSION['Email_Subject'];
$Body = $_SESSION['Email_Body'];
$Headers = $_SESSION['Email_Headers'];
$Type = $_SESSION['Type'];
msmtp($AdminEmail, $Subject, $Body, $Headers, "meyers");
if ($Type == "Catalog") {
foreach ($CatalogEmails as $AdditionalEmail) {
msmtp($AdditionalEmail, $Subject, $Body, $Headers, "meyers");
}
} else if ($Type == "Quote") {
foreach ($QuoteEmails as $AdditionalEmail) {
msmtp($AdditionalEmail, $Subject, $Body, $Headers, "meyers");
}
} else if ($Type == "Parts") {
开发者_如何学Go foreach ($PartsEmails as $AdditionalEmail) {
msmtp($AdditionalEmail, $Subject, $Body, $Headers, "meyers");
}
}
function msmtp($To, $Subject, $Body, $Headers, $Account) {
$Email = "To: $To\nSubject: $Subject\n$Headers\n\n$Body\n";
exec("echo \"$Email\" | msmtp --account=$Account $To");
}
session_destroy();
?>
I know there is a built-in PHP mail function that pretty much would take care of this, but I am running multiple SMTP servers and the msmtp
is a program I use that sends emails based on the "account" the email will be sent under. In this case it will be the "meyers" account.
All the sessions variables contain HTML (<br>
's <b>
's, etc) with some $_POST
vars in there as well. I use PHP 5.3 so no magic quotes.
I know using an echo is a horrid way, which is why I am coming to stackoverflow. My goal here is that the email will go through despite any kind of crazy character they throw at me. I know the shell/bash is picky-- I assume it's much more than just escaping double quotes.
I tried using escapeshellcmd
escapeshellarg
and htmlentities
, they all escape too much or mess up the HTML in the email.
Write the email content to a file, then redirect the file content as the input to the msmtp command.
file_put_contents($tempfile,$Email);
exec("msmtp --account=$Account $To < $tempfile");
Is PHP using the Bourne shell (sh) or Bash? In either case, it might be better if you use printf
:
exec("printf '%s' '$Email' | msmtp --account=$Account $To");
If you are using Bash, you can try the quoting feature of its printf
:
exec("printf '%q' '$Email' | msmtp --account=$Account $To");
精彩评论