Search code examples
phphtmlformshtmlspecialchars

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


I have a php contact form, which is sending data via email, and would like to sanitise it. I understand the php method for this is done with the htmlspecialchars() function.

I'm new to php and can't seem to work out how to apply this to my contact from data? Do I put my mail() function inside it?

Any assistance would be awesome.

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("[email protected]", "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>';
        }

    }
}

Solution

  • The htmlspecialchars() function is used for escaping special characters to prevent possible XSS attacks if you use this function the correct way. You may want to use this function for the message.

    For example:

    mail("[email protected]", "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>';
        }
    

    Any html you have in your message will be escaped. I suggest you to read this article aswell to get a full understanding on how to use this function properly. When used correctly, is htmlspecialchars sufficient for protection against all XSS?