为什么 php mail() 将单引号和双引号转换为它们的 html 特殊字符

Why does php mail() converts single and double quotes into their html special characters

我有一个邮件脚本可以将消息发送到我的电子邮件,但由于某种原因单引号和双引号被转换为 " 和 ',即使我没有在任何地方使用 htmlentities。为什么会这样?

<?php
    if($_POST)
    {
        $to_email = "test@gmail.com"; //Recipient email, Replace with own email here
        $subject = "E-mail from test.com website";

        //check if its an ajax request, exit if not
        if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

            $output = json_encode(array( //create JSON data
                'type'=>'error', 
                'text' => 'Sorry Request must be Ajax POST'
            ));
            die($output); //exit script outputting json data
        } 

        //Sanitize input data using PHP filter_var().
        $user_email     = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
        $message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

        if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation
            $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
            die($output);
        }

        if(strlen($message)<3){ //check emtpy message
            $output = json_encode(array('type'=>'error', 'text' => 'Too short of a message! Please enter longer something.'));
            die($output);
        }

        //email body
        $message_body = $message."\r\n\r\n-\r\nEmail : ".$user_email;

        //proceed with PHP email.
        $headers = 'From: '.$user_email.'' . "\r\n" .
        'Reply-To: '.$user_email.'' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

        $send_mail = mail($to_email, $subject, $message_body, $headers);

        if(!$send_mail)
        {
            //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
            $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
            die($output);
        } else {
            $output = json_encode(array('type'=>'message', 'text' => 'Thank you for your email.'));
            die($output);
        }
    }
?>

因为你是运行FILTER_SANITIZE_STRING。默认情况下对引号进行编码。您可以传递 flag 使其不对引号进行编码,因此请替换此行:

$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

有了这个

$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING, 
           FILTER_FLAG_NO_ENCODE_QUOTES);

它会保留你的报价。

FILTER_SANITIZE_STRING 做到了 :

$_POST["msg"]="Fish''''''''''";


   $message        = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);

echo $message ; //Fish&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;&#39;