Create captcha in PHP

  • Author: Sajjad Hossain
  • |
  • Added: Feb 05, 2016
  • |
  • In: PHP Scripts

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.
captcha.php 

<?php
@session_start();
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);
imagepng($im);
imagedestroy($im);
?>

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,

<?php
if (isset($_SESSION['captcha']) && $_SESSION['captcha'] == strtolower($_REQUEST['code'])) {
// your code
}
else
{
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
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top