Create captcha in PHP

Captcha is very important thing for human verification. We can protect our website script from web robots and spiders using captcha. Robots and spiders are unable to detect image captcha. So we can protect our important page, user form using image captcha from robots and easily can detect visitor is human. We are going to create image captcha using php. For that, we need a font file and create a script. Font helps us to style text in captcha image. We use php imagecreate function for creating this script. We provided a font with a source code of this function in this article if you want you can download this from this article’s file attachment. Now we are going to create this script. create a file name as captcha.php and put codes for this script.

header("Content-type: image/png");
$_SESSION["captcha"] = substr(md5(time()),0,5);
$im = imagecreate(110, 30);
$white = imagecolorallocate($im, 244, 255, 255);
$red = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$size = $_SESSION["captcha"];
$text = "$size";
$font = 'comic.TTF';
imagettftext($im, 20, 0, 25, 20, $red, $font, $text);
imagettftext($im, 20, 0, 25, 20, $black, $font, $text);

We use a font name as comic.TTF you can use another font if you wish. Then you need upload this font in your server. We used header(“Content-type:image/png”) for type of this php script, now this script execute result as png image. we use php session function for use this in our webpage and this session set five digits of server time’s in md5 format.
Now we are going to see how we use this captcha. If we use this captcha in a user form for human verification then we use this like this,

if (isset($_SESSION['captcha']) && $_SESSION['captcha'] == strtolower($_REQUEST['code'])) {
// your code
echo ‘<form method="post" >’;
// Other fild of form
echo '<input name="code" type="text"><br>';
echo '<img src="captcha.php" alt="captcha">';
echo '<input type="hidden" name="act" value="'.$code.'">';
echo '<input type="submit" class="submit" value="Submit">';
We can use captcha by this method. This script is ready for use. I hope this is helpful for you.

Download Source Code
Unlock source code with a social share.
Sajjad Hossain
Hi, I'm Sajjad Hossain, a PHP Developer working on PHP Development since 2012. If you have a project that you want to start you can contact me. I'm currently available for freelance work. Ping me on Facebook, WhatsApp or Skype.

We use cookies on our website. To find out more about how and why they are used or opt-out, please read our Cookie Policy. By choosing "I Accept", you consent to our use of cookies. Cookie Policy