Sat. Mar 28th, 2020


Codes for Coders

PHP captcha code by Rishap Gandhi

1 min read
PHP Captcha Code by Rishap Gandhi

PHP Captcha Code by Rishap Gandhi

PHP Captcha Code

PHP Captcha Code by Rishap Gandhi
PHP Captcha Code by Rishap Gandhi

Today I will tell you how to create the captcha code in PHP. It really simple and easy to create.

Following are the steps are needed to create the Captcha from PHP.

  1. Need one font on the server.
  2. Check PHP Image functions are working on the server
  3. Finally, create session of Captcha code.

1st Step: Install or copy font on the server

First of all, you need to download a font you can download the fonts from the followings site.

  1. 1128 Free Poster Fonts · 1001 Fonts
  2. DaFont – Download fonts
  3. Most Popular Free Fonts – FontSpace

or if you have a font then copy that font on your server.

2nd Step: Check and Install Image library

Now next step check that GD library are install on your server or not.

PHP GD Library by Rishap Gandhi
PHP GD Library by Rishap Gandhi

If GD library is not installed and follow the below link:

3rd Step: Check Session

Finally, check session is started or not if session is not started yet then start session on the captcha page.

PHP Code for the Captcha

Find the below of Captcha :

$font = "set_font_path";

$rnum = md5(uniqid(rand())); //Get a random generated number and convert that number to the md5

$code = substr($rnum, 0, 5); // Get 5 digit from the converted number

$_SESSION["captchaCode"] = $code; //Set the number in the session

$imgX = 90;

$imgY = 35;

$font_size = 20;

$angle = rand(-10, 10);

$image = imagecreate($imgX, $imgY);

$backgr_col = imagecolorallocate($image, 255, 103, 103); //Set image background color

$text_col = imagecolorallocate($image, 255, 255, 255);//Set text color

$noiceColor = imagecolorallocate($image, 255, 255, 255); // Set texture color

imagefilledrectangle($image, 0, 0, 90, 35, $backgr_col); //Create image shape and size

$box = imagettfbbox($font_size, $angle, $font, $code);

$x = (int) ($imgX - $box[4]) / 2;

$y = (int) ($imgY - $box[5]) / 2;

imagettftext($image, $font_size, $angle, $x, $y, $text_col, $font, $code);

for ($i = 0; $i < 100; $i++) {

imagesetpixel($image, rand() % 200, rand() % 50, $noiceColor);

for ($i = 0; $i < 10; $i++) {

imageline($image, mt_rand(0, $imgX), mt_rand(0, $imgY), mt_rand(0, $imgX), mt_rand(0, $imgY), $noiceColor);

header("Content-type: image/png");

imagepng($image); //Function will show the image on the browser

php captcha code

1 thought on “PHP captcha code by Rishap Gandhi

Leave a Reply

Your email address will not be published. Required fields are marked *