<?php
/*
	This is PHP file that generates CAPTCHA image for the How to Create CAPTCHA Protection using PHP and AJAX Tutorial

	You may use this code in your own projects as long as this 
	copyright is left in place.  All code is provided AS-IS.
	This code is distributed in the hope that it will be useful,
 	but WITHOUT ANY WARRANTY; without even the implied warranty of
 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
	
	For the rest of the code visit http://www.WebCheatSheet.com
	
	Copyright 2006 WebCheatSheet.com	

*/

//Start the session so we can store what the security code actually is
session_start();

//Send a generated image to the browser 
create_image(); 
exit(); 

function create_image() 
{ 
   $width    = 100;
   $height   = 38;
   $length   = 5;
   $font     = './arial.ttf';
   $font_size   = 12;
   $bg_color = array(240, 240, 240);
   $chars    = 'ABCDEFGHKMNPQRSTUVWXYZ23456789';
   //session_start();
   if (extension_loaded('gd') == false)
   {
      die("The GD extension is required for CAPTCHA!");
   }
   if (function_exists('imagettftext') == false)
   {
      die("The function 'imagettftext' is required for CAPTCHA!");
   }
   $img = imagecreatetruecolor($width, $height);
   $bkgr = imagecolorallocate($img, $bg_color[0], $bg_color[1], $bg_color[2]);
   imagefilledrectangle($img, 0, 0, $width, $height, $bkgr);

   //generate utk aproval saat register new user
   $code = '';
   for($i = 0; $i < $length; $i++)
   {
      $code .= $chr = $chars[mt_rand(0, strlen($chars)-1)];
      $r = rand(0, 192);
      $g = rand(0, 192);
      $b = rand(0, 192);
      $color = imagecolorallocate($img, $r, $g, $b);
      $rotation = rand(-35, 35);
      $x = 5+$i*(4/3*$font_size+2);
      $y = rand(4/3*$font_size, $height-(4/3*$font_size)/2);
      imagettftext($img, $font_size, $rotation, $x, $y, $color, $font, $chr);
   }
   $_SESSION['security_code'] = md5($code);

   //generate utk confirmkey
   $chars2   = 'abcdefghijklmnopqrstuvwxyz23456789';
   $length2  = 10;
   $code2 = '';
   for($i = 0; $i < $length2; $i++)
   {
      $code2 .= $chr = $chars2[mt_rand(0, strlen($chars2)-1)];
   }
   $_SESSION['confirm_code'] = $code2;

   header("Content-type: image/png");
   header("Expires: Mon, 01 Jul 1998 05:00:00 GMT");
   header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
   header("Cache-Control: no-store, no-cache, must-revalidate");
   header("Cache-Control: post-check=0, pre-check=0", false);
   header("Pragma: no-cache");

   imagepng($img);
   imagedestroy($img);

} 
?>