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

426 Replies to “How to Validate PHP form using number Captcha Image? With Insert and Mail functionality”

  1. Нужна презентация? презентация нейросеть онлайн текст Создавайте убедительные презентации за минуты. Умный генератор формирует структуру, дизайн и иллюстрации из вашего текста. Библиотека шаблонов, фирстиль, графики, экспорт PPTX/PDF, совместная работа и комментарии — всё в одном сервисе.

  2. Das Treueprogramm von NV Casino ermöglicht es Ihnen, Aktivitätsbonus zu verdienen. Die Angebote bieten einzigartige Möglichkeiten zu gewinnen und Ihr Guthaben zu erhöhen. Das kostenpflichtige Format von Spielautomaten bietet die Möglichkeit, um echtes Geld zu verdienen. Der Betreiber bietet klassische und moderne Spielautomaten mit einzigartigen Funktionen und Themen. In der Rubrik Sportwetten finden Sie Livewetten und Vorrundenspiele. Im Konto auf der NV casino website werden nicht nur der Kontostand und der Wettverlauf verfolgt. Slots, Tisch­spiele, Live-Casino, Others; alle in Euro ohne Gebühren.
    100 Gratis-Freispiele + 200% bis zu 10.000€ + 200 Freispiele 100% bis zu 2.000€ + 300 Freispiele 120% bis zu 500€ + 125 Freispiele 100% bis zu 500€ + 150 Freispiele 100% bis zu 650€ + 100 Freispiele

    References:
    https://online-spielhallen.de/verde-casimo-bonus-aktuelle-angebote-tipps/

  3. Odds display follows industry standard formats with flexible switching between decimal, fractional, and American presentations. The platform has optimized this process to minimize friction while maintaining necessary security standards. The casino requires basic personal information for account verification purposes, adhering to standard Know Your Customer (KYC) protocols.
    It provides self-tests for assessing gambling habits and useful resources for those who struggle with addiction. Win Spirit Casino Australia online promotes safe and responsible gambling. By installing the app on your device, you become eligible for the “App for Start” promotion. Note, that Winspirit casino reserves the right to block user accounts and report illegal transactions. According to the platform’s Payment Policy, all transactions must be made according to the specified amounts on the portal.

    References:
    https://blackcoin.co/ufo9-casino-your-place-to-play-your-way/

  4. I’m extremely impressed along with your writing abilities and also with the format to your weblog.

    Is that this a paid subject matter or did you modify it your self?
    Anyway keep up the excellent quality writing, it is rare to look a
    nice weblog like this one these days..

    Here is my webpage; buy cannabis online

  5. Hey I am so glad I found your website, I really found you by accident,
    while I was looking on Askjeeve for something else, Regardless I am here now and would just like
    to say many thanks for a tremendous post and
    a all round thrilling blog (I also love the theme/design), I don’t
    have time to read it all at the minute but I
    have saved it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the fantastic work.

    Also visit my site: best anal porn site

  6. Amazing! This site is truly addictive! The collection of trans porn videos is unbelievable –
    tons of stunning trans girls in high-quality scenes.
    The playback is super smooth and new videos are added frequently.

    If you’re looking to watch Free Shemale Porn porn videos featuring seductive performers and real action, this
    is definitely the perfect spot. Highly recommended!

  7. Лучшие xxx сайты предоставляют премиум-контент для зрелой
    аудитории. Исследуйте надежные источники для качества и конфиденциальности.

    my blog; BUY VIAGRA

  8. We stumbled over here different page and thought I might as well check things out.
    I like what I see so now i’m following you. Look forward to checking out your web page yet again.

    My website – Buy Rivotril

  9. Amazing! This platform is seriously addictive!
    The collection of tranny porn videos is massive –
    tons of sexy trans girls in crystal-clear scenes. The
    loading is super smooth and new content are added frequently.

    If you’re looking to watch shemale fucks guy
    porn videos featuring seductive performers and intense action, this is without a doubt the perfect spot.
    Strongly recommended!

  10. Dive into the sizzling world of lesbian GAY PORN SEX VIDEOS sex
    videos, where your deepest fantasies come alive! Discover a
    dynamic collection of 4K content, featuring captivating
    performers in intense scenes that ignite your desires.
    From provocative encounters to wild moments, each video
    is crafted to satisfy your fantasies with bold expressions of pleasure.
    Dive in for unlimited access, with smooth streaming
    and discreet privacy to fulfill your experience anytime.

    Why settle for less when you can savor the hottest lesbian porn sex videos?
    Our vast library offers exclusive content, showcasing diverse stars
    in decadent scenarios that keep your excitement racing.
    With an intuitive platform and frequent updates, you’ll
    always find scorching new videos to enjoy. No barriers—just unlimited pleasure at your fingertips.
    Experience now and let these steamy videos consume your moments!

  11. Fantastic! This site has the best anal sex Free Russian Porn videos!

    The girls get their asses stretched and the resolution is unbelievable.

    Finally found a place with true hardcore anal action. Ass
    stretching and perfect creampies.

    Greatest anal porn collection I’ve seen. The scenes are so wild and
    the girls look incredible.

    These anal sex porn videos are addictive. Passionate and mind-blowing.

    Streaming works super smooth.

    Insane anal action! Tight asses getting destroyed in the most intense way.

    Totally recommended! Absolutely addicted!

Leave a Reply

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