How To Create an Email Contact Form in PHP

In order to create a contact form on your website, with its content delivered to your mailbox, you will first need to make sure PHP's mail() function is enabled. Contact your webhosting company if it is not enabled.

img

First, let's create the html form.

<html>
<head>
    <title>Contact Us</title>
</head>
<body>

<h1>Contact Us</h1>

<form action="mail.php" method="post">
    <p>Your Name: <input type="text" name="your_name"></p>
    <p>Your Email: <input type="text" name="your_email"></p>
    <p>Subject: <input type="text" name="subject"></p>
    <p>Message: <textarea rows="5" cols="30" name="message"></textarea></p>
    <p><input type="submit" name="submit" value="Send"></p>
</form>

</body>
</html>

The form above is sending data to mail.php via POST method. In this example we are using user's Name, Email, Purpose of Contacting (Subject) and the Message.

If you would like to add more fields, just make sure you are also adding it to the mail.php file as well. The content of mail.php looks like this:

<?php
        
if(isset($_POST["submit"])) {
                
    $name = $_POST["your_name"]; //User's name
    $email = $_POST["your_email"]; //User's email
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    $from_name = "Site Name"; //From Name in email
    $from_email = "you@yoursite.com"; //Email from
    $to = "you@yoursite.com"; //Where email has to be delivered

    if( (strlen($name) < 1) || (strlen($email) < 1) || (strlen($message) < 1) ) {
                    
        echo "<strong>Error!</strong> Please fill the form completely.";

    } else {

        $email_message = "Name: ".$name."\n".
            "Email: ".$email."\n".
            "Subject: ".$subject."\n".
            "Message: ".$message."\n";

            $headers = "From: ".$from_name." <".$from_email.">\r\n";
            $headers .= "Reply-To: ".$email."\r\n";

            if(mail($to, "YourSite: $subject", $email_message, $headers, "-f".$from_email)) {
                echo "Thank you. You message has been sent.";
            } else {
                echo "Error sending email.";
            }

    }
} else {
    echo "Error in form submission.";
}

?>

The first and most important thing is to check if the form was actually submitted. It will bypass sending email if the file is accessed directly without the submission of form.

After that, we captured data sent by the form and stored in $_POST array to their respective variables. This step is not necessary, but helpful in processing code when you are writing the variables a few times.

We also declared basic stuff for the emails. The name and email from which you will receive emails as $from_name and $from_email. The $to is the email address where you want the email to be received.

Before proceeding to the email, we also need to make sure if the form was not submitted randomly without any values. For this, we will check the length of variables (strings) $name, $email, and $message. If the length is less than 1 character (means, empty), the email will not proceed. Technically, the email will be at least 6 characters if we add @domain.com in its minimum allowed lenght. But that's fine, you can increase it to 6 if you like.

When adding each variable into email, it would be wise to merge and create a new variable holding all the information we need in email. We used $email_message for that here. Notice the "\n", it will break the line and display next piece of content in new line.

You can also use reply-to and change the default "from" to the one you defined through headers. Follow the "\r\n" which is equal to pressing "enter" key. It is required by mail server.

Finally, we will use mail() function to deliver the email along with if() to check if the mail() function was processed without any errors, displaying the Thank You message or an error.

Note on Spam

Sometimes mail servers will reject your email if the "from" domain is not hosted on the originating server, or the the server doesn't attach trust header into email. Use an email address hosted on the same server as mail.php, and whitelist it in your mail client if needed.

We used additional header of "-f" with "from email" as well to stop emails delivering to SPAM. Sendmail uses it to prevent X-Warning header into email if the sender is added into trusted list.

Source code

form.php

<html>
<head>
    <title>Contact Us</title>
</head>
<body>

<h1>Contact Us</h1>

<form action="mail.php" method="post">
    <p>Your Name: <input type="text" name="your_name"></p>
    <p>Your Email: <input type="text" name="your_email"></p>
    <p>Subject: <input type="text" name="subject"></p>
    <p>Message: <textarea rows="5" cols="30" name="message"></textarea></p>
    <p><input type="submit" name="submit" value="Send"></p>
</form>

</body>
</html>

mail.php

<?php
        
if(isset($_POST["submit"])) {
                
    $name = $_POST["your_name"]; //User's name
    $email = $_POST["your_email"]; //User's email
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    $from_name = "Zahid"; //From Name in email
    $from_email = "zahid@avonix.com"; //Email from
    $to = "zahid@avonix.com"; //Where email has to be delivered

    if( (strlen($name) < 1) || (strlen($email) < 1) || (strlen($message) < 1) ) {
                    
        echo "<strong>Error!</strong> Please fill the form completely.";

    } else {

        $email_message = "Name: ".$name."\n".
            "Email: ".$email."\n".
            "Subject: ".$subject."\n".
            "Message: ".$message."\n";

            $headers = "From: ".$from_name." <".$from_email.">\r\n";
            $headers .= "Reply-To: ".$email."\r\n";

            if(mail($to, "YourSite: $subject", $email_message, $headers, "-f".$from_email)) {
                echo "Thank you. You message has been sent.";
            } else {
                echo "Error sending email.";
            }

    }
} else {
    echo "Error in form submission.";
}

?>

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?