Tuesday, December 23, 2014

Captcha in PHP

Captcha are viral these days either it be PHP or any other languages. Years before from now,  users were prompted to do simple mathematical equations and then the code checked if the user is a human or a bot but these days it has truly been replaced by captcha system which is more reliable and dynamic. Captcha is used to verify whether the reactor is a human being or it's just another bot. Captcha in PHP does not only facilates us with  visual way for security but also audio based verification. Captcha are used for saving brute force attacks and different other purposes.

Now, for example I have three files (captcha.html,captcha.php and image.php for image generation) the first is HTML file captcha.html


 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
 <meta charset="UTF-8"/>  
 <title>NGWorkshop</title>  
 </head>  
 <body>  
 <h3>Please Login:</h3>  
 <form action="picture.php" method="post">  
 <fieldset>  
 <legend>Login Form</legend>  
     Email: <input type="text" name="name"/><br/><br/>  
     Password: <input type="text" name="password"/><br/><br/>  
     Enter Code: <imgsrc="captcha.php"/><input type="text" name="captcha_code"/><br/><br/>  
 <input type="submit" name="Submit" value="Submit"/>  
 </fieldset>  
 </form>  
 </body>  
 </html> 

The next is captcha.php ,

 <?php  
 session_start();  
 $text = rand(10000,99999);  
 $_SESSION["captcha_code"] = $text;  
 $height = 40;  
 $width = 80;  
 $image_p = imagecreate($width, $height);  
 $black = imagecolorallocate($image_p, 100, 125, 140);  
 $white = imagecolorallocate($image_p, 255, 255, 255);  
 $font_size = 14;  
 imagestring($image_p, $font_size, 5, 5, $text, $white);  
 imagejpeg($image_p, null, 80);  
 ?>

Finally here goes image.php file that generates the image with the help of logic provided in captcha.php

 <?php  
 session_start();  
 if ($_POST["captcha_code"] != $_SESSION["captcha_code"] OR $_SESSION["captcha_code"]=='') {  
   echo '<strong>Incorrect Input!!!!!</strong>';  
 } else {  
   // add form data processing code here  
 echo '<strong>Verification Successful </strong>';  
 };  
 ?>

copy these files with the respective file name and put it into your servers and BOOM ! everything should work fine. If not please let me know leaving a comment ;)

No comments:

Post a Comment