tekumatlamallesh

How to Validate PHP form using number Captcha Image? With Insert and Mail functionality

To avoid robot form submissions we include captchas in the forms. we have got multiple captcha formats. like Google reCAPTCHA v2 and v3 different formats.

Now we are going to see the number captcha. After successfull validation we are going to perform the insert and mail functions automatically.

If the validation fails, then we are just showing the validation error message and not performing any insert and mail operations.

Create db and table code given below use it.

CREATE TABLE `contact1` (
  `id` int(12) NOT NULL,
  `name` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `lastname` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `email` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `phonenumber` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `city` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `message` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

In this form validation method we are going to use action self action

number_captcha.php

<?php
require_once 'PHPMailer.php';
require_once 'Exception.php';
require_once 'SMTP.php';
$mail = new PHPMailer\PHPMailer\PHPMailer();
 
session_start();
$msg = '';
  $dbhost = "localhost";
 $dbuser = "give your db username";
 $dbpass = "give your db password";
 $db = "give your db name";
  
 $conn = new mysqli($dbhost, $dbuser, $dbpass,$db);
 
// If user has given a captcha!
if (isset($_POST['input']) && sizeof($_POST['input']) > 0)
     $name=$_POST['name'];
    $lastname=$_POST['lastname'];
    $email=$_POST['email'];
    $phonenumber=$_POST['phonenumber'];
    $city=$_POST['city'];
    $message=$_POST['message'];
    // If the captcha is valid
    if ($_POST['input'] == $_SESSION['captcha'])
    {
        $msg = '<span style="color:green">SUCCESSFUL!!!</span>';
          // Query for data insertion
     $query=mysqli_query($conn, "insert into contact1(name,lastname,email,phonenumber,city,message) 
     value('$name','$lastname', '$email', '$phonenumber', '$city','$message' )");
     
    
//print_r($name);exit;
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.hostinger.com';
$mail->Port = 587;
$mail->Username = 'use smtp mail address';
$mail->Password = 'use smtp password';
$mail->SMTPAuth = true;
$mail->From = "mallesh@gmail.com";
$mail->FromName = "Malleshtekumatla";	 // name is optional

$mail->WordWrap = 50;  // set word wrap to 50 characters
$mail->IsHTML(true); // set email format to HTML
$mail->AddAddress('mallesh@gmail.com');	



$mail->Subject = "Contact Form Submitted by $name";


$mail->Body = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="https://fonts.googleapis.com/css?family=Heebo" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>

.para{
    margin: 10px;
}
</style>
</head>

<body style="margin: 0;">
	<center class="wrapper" style="width: 100%;table-layout: fixed;padding-bottom: 0px;">
		<table class="main" width="100%" style="font-size:30px; color:#41a0a2 !important;border-spacing: 0;margin: 0 auto;width: 100%;max-width: 600px;font-weight: bold;">


<!-- LOGO SECTION -->
		<tr>
			<td style="padding: 0;">
				<table width="100%" style="border-spacing: 0;">
					<tr>
						<td class="fallback-text" style="text-align: center; padding:15px; ">
							
								<span style="display: contents;"></a></span>
								<p class="para" style="display:block;line-height:34px;color:#41a0a2 !important;font-family: Verdana"></p>
								<p style="line-height:10px;font-weight: bold; padding: 0px 10px;font-size:25px;color:#d32a68;font-family: Century Gothic !important">NAME: '.$name.'</p>
									<p style="line-height:10px;font-weight: bold; padding: 0px 10px;font-size:25px;color:#d32a68;font-family: Century Gothic !important">EMAIL: '.$email.'</p>
										<p style="line-height:10px;font-weight: bold; padding: 0px 10px;font-size:25px;color:#d32a68;font-family: Century Gothic !important">CITY: '.$city.'</p>
											<p style="line-height:10px;font-weight: bold; padding: 0px 10px;font-size:25px;color:#d32a68;font-family: Century Gothic !important">PHONENUMBER: '.$phonenumber.'</p>
									<p style="line-height:10px;font-weight: bold; padding: 0px 10px;font-size:25px;color:#d32a68;font-family: Century Gothic !important">MESSAGE: '.$message.'</p>
								<a></a>
								
						</td>
					</tr>
				</table>
			</td>
		</tr>


		</table>
</center>
</body>
</html>

<div style="position:absolute;bottom: 0;width: 100%;text-align: center;line-height: 40px;font-size: 25px;">
</div>';
//if (!empty($name)||( $name != '')||(isset($name))){

	if($mail->Send())								//Send an Email. Return true on success or false on error
		{
		echo "<h2 style='text-align:center;'>Mail Sent Successfully.. <br />
		<a href='use your link'>Click Here To Go Back</a></h2>";
	            	
		}
		else
		{
			echo "<h2>Mail Not Sent.... <br />
		<a href='use your link'>Click Here To Go Back</a></h2>";
		


}

    }
    
          else{
        $msg = '<span style="color:red">CAPTCHA FAILED!!!</span>';
          }
            //print_r($_POST);exit;
  	//getting the post values

   

     
  
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>malleshtekumatla</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>

<div class="container">
 <h2>Form INSERT & Mail Function with Number  CAPTCHA  VALIDATION</h2>

 <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
                      <div class="mt-3">
           <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
    </div>
    <div class="form-group">
      <label for="text">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <div class="form-group">
      <label for="pwd">PhoneNumber:</label>
      <input type="text" class="form-control" id="" placeholder="Enter PhoneNumber" name="phonenumber">
    </div>
       <div class="form-group">
      <label for="pwd">city:</label>
      <input type="text" class="form-control" id="" placeholder="Enter City" name="city">
    </div>
        <div class="form-group">
      <label for="pwd">Message:</label>
      <input type="text" class="form-control" id="" placeholder="Enter Message" name="message">
    </div>
    <div class="checkbox">
      <label><input type="checkbox" name="remember"> Remember me</label>
    </div>
         <div style='margin:15px'>
        <img src="captcha.php">
    </div>
    
    
     <input type="text" name="input"/>
        <input type="hidden" name="flag" value="1"/>
        
        
 
        <div style='margin-bottom:5px'>
        <?php echo $msg; ?>
    </div>
     
    <div>
        Can't read the image? Click
        <a href='<?php echo $_SERVER['PHP_SELF']; ?>'>
            here
        </a>
        to refresh!
    </div>
    <button type="submit" class="btn btn-default" name="submit_btn">Submit</button>
  </form>
</div>

</body>
</html

In above file we are using captcha.php in image section. In this file we are having the random numbers generation code to display the numbers.

captcha.php

<?php

// We start a session to access
// the captcha externally!
session_start();

// Generate a random number
// from 1000-9999
$captcha = rand(1000, 9999);

// The captcha will be stored
// for the session
$_SESSION["captcha"] = $captcha;

// Generate a 50x24 standard captcha image
$im = imagecreatetruecolor(50, 24);

// Blue color
$bg = imagecolorallocate($im, 22, 86, 165);

// White color
$fg = imagecolorallocate($im, 255, 255, 255);

// Give the image a blue background
imagefill($im, 0, 0, $bg);

// Print the captcha text in the image
// with random position & size
imagestring($im, rand(1, 7), rand(1, 7),
			rand(1, 7), $captcha, $fg);

// VERY IMPORTANT: Prevent any Browser Cache!!
header("Cache-Control: no-store,
			no-cache, must-revalidate");

// The PHP-file will be rendered as image
header('Content-type: image/png');

// Finally output the captcha as
// PNG image the browser
imagepng($im);

// Free memory
imagedestroy($im);
?>

To pass this number validations we are using the sesssion concepts in this forms.

If you want to use below files

require_once ‘PHPMailer.php’;
require_once ‘Exception.php’;
require_once ‘SMTP.php’;

please check my previous tutorial link their i have provided the code related to this three files.

Click here

Leave a Reply

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