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.

Did you like this article? it will be appreciated if you share a coffee or burger with the author

Sent $5 to the author
Sent $10 to the author

Need Assistance?

I'm Sajjad Hossain, working on web application development since 2012. Do you need assistance on your project? or are you stuck with problems? I am available to help you.
If you want to contact with me ping me at -


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