How to Generate Captcha in PHP


This examples shows, how to generate Captcha using PHP Script.

First we have to Enable GD2 Library

  1. Open you php.ini file
  2. Search for following line and remove the semicolon(;).
         ;extension=php_gd2.dll
    change to
         extension=php_gd2.dll

generateCaptcha.php

<?php
  $randomNumber=rand(10000,100000);
  $image=imagecreate(75,30);
  $backGround=imagecolorallocate($image,168, 167, 165);
  $txtColor=ImageColorAllocate ($image, 250, 250, 250); 
  ImageString($image,7,15,7,$randomNumber,$txtColor);
  header("Content-type:image/png");
  imagepng($image);
  imagecolordeallocate($txtColor);
  imagecolordeallocate($backGround);
  imagedestroy($image);
?>

index.php

<html>
  <body>
    <img src="generateCaptcha.php">
  </body>
</html>

Output