Contact us text

Simple PHP contact form

In this article, you will learn on how to build simple contact form in native PHP language without adding any other frameworks or libraries.

This code may be useful when you want to build custom site or web application and your preference is to avoid any complex 3rd party tools.

You need to start with making the HTML code first. We will add such fields to the contact form in our demo:

  • First Name
  • Last Name
  • Phone
  • Email
  • Message

Of course, at the bottom of the form, there will be "Submit" button which will perform request to the server.

After submission, the back-end part of our code will collect form data and send it in plain form to the specified email address. The standard PHP's mail() function will be used for that, so please ensure that your server is properly configured and is able to send emails, otherwise, you may need to change the code and use some 3rd party mailing tools.

Now, you can see prototype of our form in the preview block below. This is just a template for the beginning. Additional code will be provided later in this article.

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Demo Preview</title>
    <meta name="description" content="Aneze Web - Demo Preview">
    <meta name="author" content="Aneze Web">

    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <form method="post">
        <input type="hidden" name="action" value="submit">
        <div class="form-row">
            <input type="text" placeholder="First Name">
        </div>
        <div class="form-row">
            <input type="text" placeholder="Last Name">
        </div>
        <div class="form-row">
            <input type="tel" placeholder="Phone">
        </div>
        <div class="form-row">
            <input type="email" placeholder="Email">
        </div>
        <div class="form-row">
            <textarea placeholder="Message"></textarea>
        </div>
        <div class="form-row">
            <input type="submit" value="Submit">
        </div>
    </form>
</body>
</html>

The next step is to make PHP code to process our contact form submissions. But, only in this example, we add it to the same file that contains the HTML form. However, in real world applications, the logic may be completely different, and PHP handlers may be placed in separate files.

<?php
session_start();

if (!empty($_POST['action']) && ($_POST['action'] == 'submit')) {
    if (!empty($_SESSION['captcha_code']) && !empty($_POST['captcha_code']) &&
        ($_SESSION['captcha_code'] == $_POST['captcha_code']))
    {
        $first_name = !empty($_POST['first_name']) ? $_POST['first_name'] : '';
        $last_name = !empty($_POST['last_name']) ? $_POST['last_name'] : '';
        $phone = !empty($_POST['phone']) ? $_POST['phone'] : '';
        $email = !empty($_POST['email']) ? $_POST['email'] : '';
        $message = !empty($_POST['message']) ? $_POST['message'] : '';

        $mail_to = 'youremail@example.com';
        $mail_subject = 'Contact form submission';
        $mail_content =
            'First Name: ' . $first_name . "\n" .
            'Last Name: ' . $last_name . "\n" .
            'Phone: ' . $phone . "\n" .
            'Email: ' . $email . "\n" .
            'Message: ' . $message . "\n";

        if (mail($mail_to, $mail_subject, $mail_content)) {
            echo '<p class="status-success">Your message has been succesfully sent.</p>';
        } else {
            echo '<p class="status-failure">Failed to send your message.</p>';
        }
    } else {
        echo '<p class="status-failure">Verification failed, numbers did not match, please try again.</p>';
    }
}
?>

Image CAPTCHA feature

As the main form code is ready at this point, we would like also to show how to make image CAPTCHA feature, so you don't get too much spam messages.

We will show several numbers in graphic format right after the form data fields. Users, once they see the numbers, should input the numbers into the text field.

Once submitted, our code will ensure that the numbers were correct, and if so, the form data will be submitted to the specified email address.

Following is the CAPTCHA code for the form:

<?php
$font_id = 5;
$width = 70;
$height = 36;
$characters = 6;

$captcha_code = strval(rand(100000, 999999));

$_SESSION["captcha_code"] = $captcha_code;

$image = imagecreatetruecolor($width, $height);
$text_color = imagecolorallocate($image, 50, 50, 50);
$background_color = imagecolorallocate($image, 255, 255, 255);
$line_color = imagecolorallocate($image, 120, 120, 120);
$pixel_color = imagecolorallocate($image, 0, 0, 255);

imagefill($image, 0, 0, $background_color);
imagestring(
    $image,
    $font_id,
    ($width - $characters*imagefontwidth($font_id)) / 2,
    ($height - imagefontheight($font_id)) / 2,
    $captcha_code,
    $text_color);

for ($i = 0; $i < 5; $i++) {
    imageline(
        $image,
        0,
        rand() % $height,
        $width,
        rand() % $height,
        $line_color);
}

for ($i = 0; $i < 200; $i++) {
    imagesetpixel(
        $image,
        rand() % $width,
        rand() % $height,
        $pixel_color);
}

ob_start();
imagepng($image, null, 9, PNG_NO_FILTER);
$image_prefix = 'data:image/png;base64,';
$image_content = $image_prefix . base64_encode(ob_get_contents());
imagedestroy($image);
ob_end_clean();
?>

Now, we need to show the CAPTHCA image and the input field:

<img alt="" class="captcha-image" src="<?php echo $image_content ?>">
<input type="text"
    class="captcha-input"
    name="captcha_code"
    placeholder="Enter number"
    maxlength="<?php echo $characters ?>"
    size="<?php echo $characters ?>">

Final version of the contact form

Following are the custom CSS styles for our demo project. We've created them to make the form looking more attractive, so you don't see standard input fields.

html {
    margin: 0px;
    padding: 0px;
    background: #f0f0f0;
    font-family: Arial, Helvetica, sans-serif;
}

body {
    margin: 0px;
    padding: 20px 20px 0px 20px;
}

img {
    border: none;
}

.form-row {
    margin: 0px 0px 20px 0px;
}

.form-row:last-child {
    margin: 0px;
}

textarea {
    min-height: 100px;
}

textarea,
input[type="text"],
input[type="tel"],
input[type="email"] {
    padding: 8px 12px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    line-height: 20px;
    color: #555555;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #d0d0d0;
    transition: border-color 0.3s ease-out 0s;
    outline: 0;
    width: 270px;
    max-width: 100%;
}

textarea:focus,
input[type="text"]:focus,
input[type="tel"]:focus,
input[type="email"]:focus {
    border: 1px solid #ffa050;
}

button,
input[type="button"],
input[type="submit"] {
    padding: 8px 30px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    line-height: 20px;
    color: #ffffff;
    background: #ff7000;
    border-radius: 4px;
    border: 1px solid #d0d0d0;
    cursor: pointer;
    transition: opacity 0.3s ease-out 0s;
    outline: 0;
}

button:hover,
input[type="button"]:hover,
input[type="submit"]:hover {
    opacity: 0.8;
}

.status-success {
    color: #30e030;
}

.status-failure {
    color: #e03030;
}

form img.captcha-image {
    margin: 0px 15px 0px 0px;
    vertical-align: middle;
}

form input.captcha-input {
    max-width: 100px;
    vertical-align: middle;
}

You can see the final version of our HTML and PHP code in the preview window below:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Demo Preview</title>
    <meta name="description" content="Aneze Web - Demo Preview">
    <meta name="author" content="Aneze Web">

    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
<?php
session_start();

if (!empty($_POST['action']) && ($_POST['action'] == 'submit')) {
    if (!empty($_SESSION['captcha_code']) && !empty($_POST['captcha_code']) &&
        ($_SESSION['captcha_code'] == $_POST['captcha_code']))
    {
        $first_name = !empty($_POST['first_name']) ? $_POST['first_name'] : '';
        $last_name = !empty($_POST['last_name']) ? $_POST['last_name'] : '';
        $phone = !empty($_POST['phone']) ? $_POST['phone'] : '';
        $email = !empty($_POST['email']) ? $_POST['email'] : '';
        $message = !empty($_POST['message']) ? $_POST['message'] : '';

        $mail_to = 'youremail@example.com';
        $mail_subject = 'Contact form submission';
        $mail_content =
            'First Name: ' . $first_name . "\n" .
            'Last Name: ' . $last_name . "\n" .
            'Phone: ' . $phone . "\n" .
            'Email: ' . $email . "\n" .
            'Message: ' . $message . "\n";

        if (mail($mail_to, $mail_subject, $mail_content)) {
            echo '<p class="status-success">Your message has been succesfully sent.</p>';
        } else {
            echo '<p class="status-failure">Failed to send your message.</p>';
        }
    } else {
        echo '<p class="status-failure">Verification failed, numbers did not match, please try again.</p>';
    }
}
?>
    <form method="post">
        <input type="hidden" name="action" value="submit">
        <div class="form-row">
            <input type="text" name="first_name" placeholder="First Name">
        </div>
        <div class="form-row">
            <input type="text" name="last_name" placeholder="Last Name">
        </div>
        <div class="form-row">
            <input type="tel" name="phone" placeholder="Phone">
        </div>
        <div class="form-row">
            <input type="email" name="email" placeholder="Email">
        </div>
        <div class="form-row">
            <textarea name="message" placeholder="Message"></textarea>
        </div>
        <div class="form-row">
            <?php
            $font_id = 5;
            $width = 70;
            $height = 36;
            $characters = 6;

            $captcha_code = strval(rand(100000, 999999));

            $_SESSION["captcha_code"] = $captcha_code;

            $image = imagecreatetruecolor($width, $height);
            $text_color = imagecolorallocate($image, 50, 50, 50);
            $background_color = imagecolorallocate($image, 255, 255, 255);
            $line_color = imagecolorallocate($image, 120, 120, 120);
            $pixel_color = imagecolorallocate($image, 0, 0, 255);

            imagefill($image, 0, 0, $background_color);
            imagestring(
                $image,
                $font_id,
                ($width - $characters*imagefontwidth($font_id)) / 2,
                ($height - imagefontheight($font_id)) / 2,
                $captcha_code,
                $text_color);

            for ($i = 0; $i < 5; $i++) {
                imageline(
                    $image,
                    0,
                    rand() % $height,
                    $width,
                    rand() % $height,
                    $line_color);
            }

            for ($i = 0; $i < 200; $i++) {
                imagesetpixel(
                    $image,
                    rand() % $width,
                    rand() % $height,
                    $pixel_color);
            }

            ob_start();
            imagepng($image, null, 9, PNG_NO_FILTER);
            $image_prefix = 'data:image/png;base64,';
            $image_content = $image_prefix . base64_encode(ob_get_contents());
            imagedestroy($image);
            ob_end_clean();
            ?>
            <img alt="" class="captcha-image" src="<?php echo $image_content ?>">
            <input type="text"
                class="captcha-input"
                name="captcha_code"
                placeholder="Enter number"
                maxlength="<?php echo $characters ?>"
                size="<?php echo $characters ?>">
        </div>
        <div class="form-row">
            <input type="submit" value="Submit">
        </div>
    </form>
</body>
</html>

You can copy and save our HTML form example into the PHP file, add CSS styles and upload everything to your server and run in browser. After that, you should see the form, which would be similar to our demo preview below:

Visual Preview

Thank you for reading this article. Our goal is to help you learning web development, so you can make better web applications and sites.

Related Articles

Source code on computer

How to select an element by name in jQuery

One way sign

How to detect which radio button is selected

Comments

2 replies to “Simple PHP contact form”

  • Kim says:

    Hi, I went to copy the entire code down but I believe there's still something wrong with the CAPTCHA. No matter how many times I double-triple check the CAPTCHA before submitting, the form still says it's wrong.

    • Aneze says:

      Hello, you may try to debug the code and see what's wrong. The good idea is to check the session and post data.

Leave a Reply

Your email address will not be published. Required fields are marked *