First of all, captcha is for spam prevention. When there is a form in your website that site visitors allowed to give their inputs, you could be very careful. There is a robot might pretend to be a human and feed the details. People will post bulk data to your site, leads to your site a mess.
Even XSS attacks or unwanted load on your site will be a nightmare for the web admins.
This tutorial has small user register form, that has inputs like first name, last name, email, password. I will use random captcha code that will part of this form.
The user needs to input the captcha if they want to submit their details. Our captcha is an image, so a robot can’t read that image.
Generate captcha image in PHP
<?php session_start(); $code=mt_rand(1000,9999); $_SESSION["captcha_code"]=$code; $im = imagecreatetruecolor(50, 24); $bg = imagecolorallocate($im, 0, 0, 0); //background color black $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); ?>
PHP image Captcha in an HTML form
<html> <head> <title>Captcha form</title> </head> <body> <form method="post" action="form_validate.php"> <div class="form-group"> <label for="firstname">Firstname</label> <input type="text" class="form-control" id="firstname" name="firstname"> </div> <div class="form-group"> <label for="lastname">Firstname</label> <input type="text" class="form-control" id="firstname" name="lastname"> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" class="form-control" id="email" name="email"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" id="password" name="password"> </div> <div class="form-group"> <label for="captcha_code">Enter the code</label> <input type="text" class="form-control" id="captcha_code" name="captcha_code"> <img src="captcha.php" /><br> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </body> </html>
Validating the PHP image captcha in form validation
<?php session_start(); if($_SERVER['REQUEST_METHOD'] == 'POST') { if($_POST['captcha_code'] == $_SESSION['captcha_code']) { //do your success stuff print "Go ahead"; } else { print "You are not a human"; exit; } }
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply