PHP

Contact Form With Captcha

Contact Form With Captcha:

Captcha Code is in a form is used for ensuring that the form is being submitted by human being not by any tools or program. During entering the data into our website , we need to check whether the data is being entered by human being or robots or any automated tools.

It is important to check before entering any data into our website because it will cause a lot problems . For example, sometimes it will increase server load time and let it down.

Captcha is one of the best way to validate form for such a situation.

What Is Captcha?
https://en.wikipedia.org/wiki/CAPTCHA
How To Create Captcha In PHP.

We will use the PHP GD library to create our CAPTCHA. This library is used for dynamic image creation. In PHP we can create PNG, JPEG or GIF image instantly. To create captcha in PHP you have to enable GD library. You can check it whether it is enable or disable using phpinfo().

Step 1 : Generate Random String.

All the code from this will go in captcha.php. Let’s start the code to create random string.

<?php

$str = '012345ABCDEFGHIJ765439KLMNOPQRS0984351TUVWXYZ876542';
$rand = rand(0,20); 
$captcha_code = substr(str_shuffle($str),$rand,6);

?>


The str variable stores all the characters that we want to use to create a our CAPTCHA string. We create six letters of string , you can change it to any length of string. Here I use PHP rand() function to generate a random number and based on thiss random number I create a random CAPTCHA string by using str_shuffle and substr PHP inbuilt function.

Step 2 : Render the CAPTCHA Background.

Once we have a random string it’s time to create a code to add the background of the CAPTCHA image. The image will be 150 X 50 pixels.

<?php

if(!function_exists('gd_info') ) {
        throw new Exception('Required GD library is missing');
    }	
   
$layer = imagecreatetruecolor(150, 50);
$bg_color = imagecolorallocate($layer, 255, 255, 255);  ; 
$fg_color = imagecolorallocate($layer, 0,0,0);
$line_color =  imagecolorallocate($layer, 64,64,64);   
$pixel_color = imagecolorallocate($layer, 255,125,325);
for($i=0;$i<1500;$i++) {
    imagesetpixel($layer,rand()%150,rand()%50,$pixel_color);
} 

imagefill($layer, 0, 0, $bg_color);  
imagestring($layer, 5, 7,9, $captcha_code, $fg_color); 



?>
Final Code Of Captcha File :
<?php

session_start();
header("Cache-Control: no-store,no-cache, must-revalidate");  
header('Content-type: image/png'); 
$str = '012345ABCDEFGHIJ765439KLMNOPQRS0984351TUVWXYZ876542';
$rand = rand(0,20); 
$captcha_code = substr(str_shuffle($str),$rand,6);
$_SESSION["code"] = $captcha_code;
 if(!function_exists('gd_info') ) {
        throw new Exception('Required GD library is missing');
    }	
   
$layer = imagecreatetruecolor(150, 50);
$bg_color = imagecolorallocate($layer, 255, 255, 255);  ; 
$fg_color = imagecolorallocate($layer, 0,0,0);
$line_color =  imagecolorallocate($layer, 64,64,64);   
$pixel_color = imagecolorallocate($layer, 255,125,325);
for($i=0;$i<1500;$i++) {
    imagesetpixel($layer,rand()%150,rand()%50,$pixel_color);
} 

imagefill($layer, 0, 0, $bg_color);  
imagestring($layer, 5, 7,9, $captcha_code, $fg_color); 
imagepng($layer);  
imagedestroy($layer); 

?>
Final Step : Add The CAPTCHA To Our Contact Form.
<?php 
session_start();
if(isset($_POST['submit'])){
	if($_POST['captcha']!=$_SESSION['code']){
	
		echo "<center><span style=color:red;font-size:15px>Invalid Captcha Code</center></span>";
	}else{
		 
		echo "<pre>";
		print_r($_POST);exit;
	}
}
?>
<html lang="en">
<head>
  <title>Contact Form With Captcha</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
  <style type="text/css">
  #multistep_form fieldset:not(:first-of-type) {
    display: none;
  }
  </style>
</head>
<body>

<h3 class="text-success" align="center">Contact Form With Captcha</h3><br>
<div class="container">
   
  <div class="panel-group">
    <div class="panel panel-primary">
     <div class="panel-heading">Contact Form With Captcha</div>
        <form class="form-horizontal" method="post">         
            <div class="panel-body">                 
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="Name">Name:</label>
                        <div class="col-sm-5">
                          <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="email">Email:</label>
                        <div class="col-sm-5"> 
                          <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                    </div>  
					<div class="form-group">
							<label class="control-label col-sm-2" for="mobno">Mobile Number:</label>
							<div class="col-sm-5">
							  <input type="number" class="form-control" id="mobno" name="mobno" required>
							</div>
					</div>
                <div class="form-group">
                        <label class="control-label col-sm-2" for="contact">Comment:</label>
                        <div class="col-sm-5">
                          <textarea   class="form-control" id="contact" name="contact"></textarea>
                        </div>
                </div>
                <div class="form-group">
                        <label class="control-label col-sm-2" for="contact">Captcha Code:</label>
                        <div class="col-sm-3">
                          <input type="text" class="form-control" id="captcha" name="captcha" required>
                        </div>
						<div class="col-sm-2"><img src="captcha.php" id="captcha_id"></div>
						<div class="col-sm-2"><i class="fa fa-refresh" 
						 onclick="document.getElementById('captcha_id').src = 'captcha.php'; return false"
						 style="font-size:25px;color:red;cursor:pointer"></i>
						</div>

                </div>
                
                <input type="submit"  name="submit" class="next btn btn-success" value="SUBMIT" id="submit" style='margin-left:30%'/>
            </div>                         
        </form>
      </div>
    </div>
</div> 
</body> 
</html>

Create Month Dropdwon Using Date Function In PHP.

Please give your valuable feedback/comments about this article below. Please let me know how you like and understand this article and how I could improve it.

Related Articles

Leave a Reply

Back to top button