如何在 php 联系表单上使用 htmlspecialchars() 函数(即使用 mail() 函数)

How to use htmlspecialchars() function on a php contact form (that is using the mail() function)

我有一个 php 联系表,它正在通过电子邮件发送数据,我想对其进行清理。我知道 php 方法是通过 htmlspecialchars() 函数完成的。

我是 php 的新手,似乎无法弄清楚如何将此应用到我的数据联系人?我是否将 mail() 函数放入其中?

任何帮助都会很棒。

PHP

if($_POST['submit']) {

    if(!$_POST['name']) {
        $error="<br>- Please enter your name";
    }
    if(!$_POST['email']) {
        $error.="<br>- Please enter your email";
    }
    if(!$_POST['telephone']) {
        $error.="<br>- Please enter your telephone number";
    }
    if(!$_POST['message']) {
        $error.="<br>- Please enter your message";
    }
    if(!$_POST['radio']) {
        $error.="<br>- Please confirm you agree to the Privacy Policy";
    }

    if ($error) {
        $result='<div class="alert error">Whoops, there is an error. Please correct the following: '.$error.'</div>';
    } else {
        mail("example@example.com", "Contact Message", "Name: ".$_POST['name']."
        Email: ".$_POST['email']."
        Telephone: ".$_POST['telephone']."
        Company: ".$_POST['company']."
        Budget: ".$_POST['budget']."
        Message: ".$_POST['message']);

        {
            $_POST= array();
            $result='<div class="alert thankyou" role="alert">THANK YOU! WE\'LL BE IN TOUCH SHORTLY...</div>';
        }

    }
}

htmlspecialchars()函数用于转义特殊字符,以防止可能的XSS攻击,如果您正确使用该函数的话。您可能希望将此函数用于 message

例如:

mail("example@example.com", "Contact Message", "Name: ".htmlspecialchars($_POST['name'])."
    Email: ".htmlspecialchars($_POST['email'])."
    Telephone: ".htmlspecialchars($_POST['telephone'])."
    Company: ".htmlspecialchars($_POST['company'])."
    Budget: ".htmlspecialchars($_POST['budget'])."
    Message: ".htmlspecialchars($_POST['message']));

    {
        $_POST= array();
        $result='<div class="alert thankyou" role="alert">THANK YOU! WE\'LL BE IN TOUCH SHORTLY...</div>';
    }

您的消息中的任何 html 都将被转义。我建议您也阅读这篇文章,以全面了解如何正确使用此功能。 When used correctly, is htmlspecialchars sufficient for protection against all XSS?