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

时间:2015-01-08 01:46:22

标签: php email

我有一个邮件脚本可以向我的电子邮件发送邮件,但出于某种原因,即使我不在任何地方使用htmlentities,单引号和双引号也会转换为&#34和&#39。为什么会这样?

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

2 个答案:

答案 0 :(得分:2)

这是因为您正在运行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);

它会留下你的报价。

答案 1 :(得分:1)

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;