Get complete CodeIgniter blog project for free!

Downloaded more than 161 times, this is full project must-study for serious developers!

By submitting this form, you agree to our Terms of Service and Privacy Policy.

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.

Search on PHPAns
Subscribe to PHPAns
Join with our 32000+ subscribers and get our latest articles in your email inbox for free.
Delivered by FeedBurner
We always respect your privacy and take protecting it seriously.
Connect Social With PHPAns