How to create PHP contact form script with captcha

In the two previous posts, we have successfully created a simple contact form with validation for fields. It can’t be denied that a lot of spammers and programmed spambots will attack your website from flooding your form, that’s the reason why your contact form needs a CAPTCHA function to prevent those spam emails. By using captcha function, a customer needs to enter correct provided characters into the captcha box so that they can submit his request to the server. In this article, I will guide you how to create the PHP contact form script with captcha.

PHP contact form script with captcha

We will create contact-us.php file instead of HTML file. You need to put this .php file into the project folder.

Source code of PHP contact form script with captcha:


<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="TRAN DINH HONG" />
<title>php code to send email from contact form</title>
<link type="text/css" rel="stylesheet" href="style/style.css" />
</head>
 
<body>
<?php
session_start();
 
include("php/simple-php-captcha/simple-php-captcha.php");
// Step 1 - Enter your email address below.
$to = 'you@domain.com';
 
if(isset($_POST['emailSent'])) {
 
$subject = $_POST['subject'];
 
// Step 2 - If you don't want a "captcha" verification, remove that IF.
if (strtolower($_POST["captcha"]) == strtolower($_SESSION['captcha']['code'])) {
 
$name = $_POST['name'];
$email = $_POST['email'];
 
// Step 3 - Configure the fields list that you want to receive on the email.
$fields = array(
0 => array(
'text' => 'Name',
'val' => $_POST['name']
),
1 => array(
'text' => 'Email address',
'val' => $_POST['email']
),
2 => array(
'text' => 'Message',
'val' => $_POST['message']
),
3 => array(
'text' => 'Checkboxes',
'val' => implode($_POST['checkboxes'], ", ")
),
4 => array(
'text' => 'Radios',
'val' => $_POST['radios']
)
);
 
$message = "";
 
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
 
$mail = new PHPMailer;
$mail->From = $email;
$mail->FromName = $_POST['name'];
$mail->AddAddress($to);
$mail->AddReplyTo($email, $name);
 
$mail->IsHTML(true);
 
$mail->CharSet = 'UTF-8';
 
$mail->Subject = $subject;
$mail->Body    = $message;
 

// Step 5 - If you don't want to attach any files, remove that code below

if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']);
}
 
if($mail->Send()) {
$arrResult = array('response'=> 'success');
} else {
$arrResult = array('response'=> 'error', 'error'=> $mail->ErrorInfo);
}
 
} else {
 
$arrResult['response'] = 'captchaError';
 
}
 
}
?>
 
<div class="contact-wapper">
<h2 class="title"><strong>Contact</strong> Us</h2>

<form id="contactForm" action="<?php echo basename($_SERVER['PHP_SELF']); ?>#contact-sent" method="POST" >

<div class="row">

<div class="form-group">

<div class="col-md-6">

<label>Your name *</label>

<input type="text" value="" msg-error="Please enter your name here."  maxlength="100" class="form-control" name="name" id="name" required="" aria-required="true">

</div>

<div class="col-md-6">

<label>Your email address *</label>

<input type="email" value="" msg-error="Please enter your email address here."  maxlength="100" class="form-control" name="email" id="email" required="" aria-required="true">

</div>

</div>

</div>

<div class="row">

<div class="form-group">

<div class="col-md-12">

<label>Subject</label>

<input type="text" value="" msg-error="Please enter your subject  here."  maxlength="100" class="form-control" name="subject" id="subject" required="" aria-required="true">

</div>

</div>

</div>

<div class="row">

<div class="form-group">

<div class="col-md-12">

<label>Message *</label>

<textarea maxlength="5000" rows="10" msg-error="Please enter your message  here." class="form-control" name="message" id="message"  required="" aria-required="true"></textarea>

</div>

</div>

</div>

<div class="row">

<div class="col-md-12">

<label>Capcha code*</label>

</div>

</div>

<div class="row">

<div class="form-group capcha-s">

<div class="col-md-4">

<div class="captcha form-control">

<div class="captcha-image">

<?php

$_SESSION['captcha'] = simple_php_captcha(array(

'min_length' => 6,

'max_length' => 6,

'min_font_size' => 22,

'max_font_size' => 22,

'angle_max' => 3

));
$_SESSION['captchaCode'] = $_SESSION['captcha']['code'];
echo '<img id="captcha-image" src="' . "php/simple-php-captcha/simple-php-captcha.php/" . $_SESSION['captcha']['image_src'] . '" alt="CAPTCHA code">';
?>
</div>
<div class="captcha-refresh">
<a href="#" id="refreshCaptcha"><i class="fa fa-refresh"></i></a>
</div>
</div>
</div>
<div class="col-md-8">
<input type="text" value="" maxlength="6" data-msg-captcha="Wrong verification code." data-msg-required="Please enter the verification code." placeholder="Type capcha code." class="form-control input-lg captcha-input" name="captcha" id="captcha" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" value="Send Message" class="btn btn-primary btn-lg mb-xlg" />
</div>
</div>
</form>
</div>
</body>
</html>

Please take note about this important code line: “include(“php/simple-php-captcha/simple-php-captcha.php”);”. This means we need to use the PHP captcha library to automatically generate captcha code for each customer if we develop the PHP contact form script with captcha.

In this article, we talk about the basic things that help you understand how it works. In reality, you can base on this article to learn how to add a library to create the captcha function. Because the contents of the library are so long and complicated that users who start to learn about form find it difficult to understand, we will talk about it in another article.

You shouldn’t follow the post if you are using a framework like WordPress, Prestashop or Magento. Because the frameworks has awsome plugins, modules for creating form. For example, If you need custom Prestashop contact form, you could use module Form Builder Pro.

There are many types of captcha that can be used. We will discuss one captcha type in this article. Besides, another interesting way is using Google captcha. Basically, we need to register to get API of Google then add this API to the form settings in order o be able to use.

you can download Source code : PHP-contact form-script-with-captcha

If you’ve any question or recommendation, please do not hesitate to let us know.

 

Enjoy this blog? Please spread the word :)