How to integrate simple PHP CAPTCHA script?

Many times public form will spam data. We can prevent spamming data using PHP CAPTCHA script. We can Integrate PHP CAPTCHA script with email form, contact us form, registration form, login page etc..

Example :

Filename : captcha.php

<?php
session_start();
$code=rand(1000,9999);
$_SESSION["code"]=$code;
$im = imagecreatetruecolor(50, 24);
$bg = imagecolorallocate($im, 22, 86, 165); //background color blue
$fg = imagecolorallocate($im, 255, 255, 255);//text color white
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 5, 5,  $code, $fg);
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Filename : contact.php

<form action="submit.php" method="post" id="consultationfrm">

    <p style="color:#FF0000;font-size:16px"><?=$msg ?>
  </p>
  <p>Fill out the form below, and one of our experts will get in touch with you shortly.
     <br>
    <input type="hidden"  name="Subject" value="Contact Us" >
    Name
  <input type="text" name="Name" placeholder="Enter you name" required>
  </p>
  <p>
    Email
    <input type="text" name="Email" placeholder="Enter your email address" required>
  </p>
  <label></label>
  <p><br>
    Phone Number
    <input type="text" name="Phone" class="phoneUS" placeholder="Enter your phone number" required>
  </p>
  <p>Message
    <textarea placeholder="Enter Message" name="Message"></textarea>
  </p>
  <p>  Enter Captcha Code   <img src="captcha.php" />
        <input name="captcha" type="text" required>
  </p>
    <input type="submit" id="consultation_submit" name="consultation_submit" value="Send Request">
  </form>

Filename : submit.php

<?php
session_start();
if(isset($_REQUEST['consultation_submit']))
{
    
    if($_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
    {
     //code to be executed
     $msg="Your Form has been submitted successfully.";
    }else
    {
        $msg="Please enter correct captcha code!!!";
    }
}    
?>

Comments

Leave a Reply

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

63067