ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

How to Create a Captcha Image in PHP

captchaIMgFormatIn this tutorial, I will teach you how to create a captcha in PHP Captcha mostly seen if you are going to register or download in a website. This is a test for security purpose of a certain website to find out if the webuser is an adult or under age. Because there are some website that is for adults only and young web users are not allowed to access it.

 

Lets begin:

 

  • First, create a class for creating captcha image. Name it “loadcaptcha.php”.
  1. /** initialize */
  2. $createcaptcha = new  CAPTCHA_LOADER();
  3. /** load image */
  4. $createcaptcha->Load_Image();
  5.  
  6. class CAPTCHA_LOADER {
  7.  
  8. /** set the width of the image */
  9. public $img_width  = 250;
  10.  
  11. /** set the height of the image */
  12. public $img_height = 50;
  13.  
  14. /** set the dictionary word file  */
  15. public $words_File = 'words/en.php';
  16.  
  17. /**
  18. * set a path for resource files (fonts, words, etc.)
  19. */
  20. public $path = 'captcha-resources';
  21.  
  22. /** set the min word length  */
  23. public $min_Word_Length = 4;
  24.  
  25. /**
  26. * set the max word length
  27. */
  28. public $max_Word_Length = 9;
  29.  
  30. /** set the session name to store the original text */
  31. public $session_variable = 'captcha';
  32.  
  33. /** set the background color in RGB-array */
  34. public $background_Color = array(255, 255, 255);
  35.  
  36. /** set foreground colors in RGB-array */
  37. public $txtcolors = array(
  38. array(27,78,181), // blue
  39. array(22,163,35), // green
  40. array(214,36,7),  // red
  41. );
  42.  
  43. /** set the shadow color in RGB-array or null */
  44. public $txtshadowColor = null; //array(0, 0, 0);
  45.  
  46. /** set the horizontal line through the text */
  47. public $line_Width = 0;
  48.  
  49. /**
  50. * set the font configuration
  51. */
  52. public $fonts = array(
  53. 'Antykwa'  => array('spacing' => -3, 'minSize' => 27, 'maxSize' => 30, 'font' => 'AntykwaBold.ttf'),
  54. 'Candice'  => array('spacing' =>-1.5,'minSize' => 28, 'maxSize' => 31, 'font' => 'Candice.ttf'),
  55. 'Times'    => array('spacing' => -2, 'minSize' => 28, 'maxSize' => 34, 'font' => 'TimesNewRomanBold.ttf'),
  56. 'VeraSans' => array('spacing' => -1, 'minSize' => 20, 'maxSize' => 28, 'font' => 'VeraSansBold.ttf'),
  57. 'Duality'  => array('spacing' => -2, 'minSize' => 30, 'maxSize' => 38, 'font' => 'Duality.ttf'),
  58. 'Heineken' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 34, 'font' => 'Heineken.ttf'),
  59. 'Jura'     => array('spacing' => -2, 'minSize' => 28, 'maxSize' => 32, 'font' => 'Jura.ttf'),
  60. 'StayPuft' => array('spacing' =>-1.5,'minSize' => 28, 'maxSize' => 32, 'font' => 'StayPuft.ttf'),
  61. 'DingDong' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 30, 'font' => 'Ding-DongDaddyO.ttf'),
  62. );
  63.  
  64. /** set the wave configuracion in X and Y axes */
  65. public $y_axis    = 10;
  66. public $y_amplitude = 12;
  67. public $x_axis    = 9;
  68. public $x_amplitude = 3;
  69.  
  70. /** letter rotation clockwise */
  71. public $max_rotation = 10;
  72.  
  73. /**
  74. * set the internal image size factor
  75. */
  76. public $img_scale =1 ;
  77.  
  78. /**
  79. * set the blur effect for better image quality (slower image process).
  80. */
  81. public $img_blur = false;
  82.  
  83. /** Debug image? */
  84. public $img_debug = false;
  85.  
  86. /** set image format: jpeg or png */
  87. public $imgFormat = 'jpeg';
  88.  
  89. /** set  GD image */
  90. public $gd_Image;
  91.  
  92. public function __construct($config = array()) {
  93. }
  94.  
  95. public function Load_Image() {
  96. $ini = microtime(true);
  97.  
  98. /** Initialization */
  99. $this->Image_Allocate();
  100.  
  101. /** Text insertion */
  102. $text = $this->GetCaptchaText();
  103. $fontcfg  = $this->fonts[array_rand($this->fonts)];
  104. $this->Write_Text($text, $fontcfg);
  105.  
  106. $_SESSION[$this->session_variable] = $text;
  107.  
  108. /** Transformations */
  109. if (!empty($this->line_Width)) {
  110. $this->Write_Line();
  111. }
  112. $this->Wave_Image();
  113. if ($this->img_blur && function_exists('imagefilter')) {
  114. imagefilter($this->gd_Image, IMG_FILTER_GAUSSIAN_BLUR);
  115. }
  116. $this->Reduce_Image();
  117.  
  118. if ($this->img_debug) {
  119. imagestring($this->gd_Image, 1, 1, $this->img_height-8,
  120. "$text {$fontcfg['font']} ".round((microtime(true)-$ini)*1000)."ms",
  121. $this->GdFgColor
  122. );
  123. }
  124.  
  125. /** Output */
  126. $this->Write_Image();
  127. $this->CleaningUp();
  128. }
  129.  
  130. /**
  131. * Creates the image resources
  132. */
  133. protected function Image_Allocate() {
  134. // Cleaning Up
  135. if (!empty($this->gd_Image)) {
  136. imagedestroy($this->gd_Image);
  137. }
  138.  
  139. $this->gd_Image = imagecreatetruecolor($this->img_width*$this->img_scale, $this->img_height*$this->img_scale);
  140.  
  141. // Background color
  142. $this->GdBgColor = imagecolorallocate($this->gd_Image,
  143. $this->background_Color[0],
  144. $this->background_Color[1],
  145. $this->background_Color[2]
  146. );
  147. imagefilledrectangle($this->gd_Image, 0, 0, $this->img_width*$this->img_scale, $this->img_height*$this->img_scale, $this->GdBgColor);
  148.  
  149. // Foreground color
  150. $color           = $this->txtcolors[mt_rand(0, sizeof($this->txtcolors)-1)];
  151. $this->GdFgColor = imagecolorallocate($this->gd_Image, $color[0], $color[1], $color[2]);
  152.  
  153. // Shadow color
  154. if (!empty($this->txtshadowColor) && is_array($this->txtshadowColor) && sizeof($this->txtshadowColor) >= 3) {
  155. $this->GdShadowColor = imagecolorallocate($this->gd_Image,
  156. $this->txtshadowColor[0],
  157. $this->txtshadowColor[1],
  158. $this->txtshadowColor[2]
  159. );
  160. }
  161. }
  162.  
  163. /**
  164. * create a text generation
  165. */
  166. protected function GetCaptchaText() {
  167. $text = $this->GetCaptchaTextDictionary();
  168. if (!$text) {
  169. $text = $this->GetRandomCaptchaText();
  170. }
  171. return $text;
  172. }
  173.  
  174. /**
  175. * set a random text generation
  176. */
  177. protected function GetRandomCaptchaText($length = null) {
  178. if (empty($length)) {
  179. $length = rand($this->min_Word_Length, $this->max_Word_Length);
  180. }
  181.  
  182. $words  = "abcdefghijlmnopqrstvwyz";
  183. $vocals = "aeiou";
  184.  
  185. $text  = "";
  186. $vocal = rand(0, 1);
  187. for ($i=0; $i<$length; $i++) {
  188. if ($vocal) {
  189. $text .= substr($vocals, mt_rand(0, 4), 1);
  190. } else {
  191. $text .= substr($words, mt_rand(0, 22), 1);
  192. }
  193. $vocal = !$vocal;
  194. }
  195. return $text;
  196. }
  197.  
  198. /**
  199. * set a random dictionary word generation
  200. */
  201. function GetCaptchaTextDictionary($extended = false) {
  202. if (empty($this->words_File)) {
  203. return false;
  204. }
  205.  
  206. // Full path of words file
  207. if (substr($this->words_File, 0, 1) == '/') {
  208. $words_file = $this->words_File;
  209. } else {
  210. $words_file = $this->path.'/'.$this->words_File;
  211. }
  212.  
  213. if (!file_exists($words_file)) {
  214. return false;
  215. }
  216.  
  217. $fp     = fopen($words_file, "r");
  218. $length = strlen(fgets($fp));
  219. if (!$length) {
  220. return false;
  221. }
  222. $line   = rand(1, (filesize($words_file)/$length)-2);
  223. if (fseek($fp, $length*$line) == -1) {
  224. return false;
  225. }
  226. $text = trim(fgets($fp));
  227. fclose($fp);
  228.  
  229. /** Change ramdom volcals */
  230. if ($extended) {
  231. $text   = preg_split('//', $text, -1, PREG_SPLIT_NO_EMPTY);
  232. $vocals = array('a', 'e', 'i', 'o', 'u');
  233. foreach ($text as $i => $char) {
  234. if (mt_rand(0, 1) && in_array($char, $vocals)) {
  235. $text[$i] = $vocals[mt_rand(0, 4)];
  236. }
  237. }
  238. $text = implode('', $text);
  239. }
  240.  
  241. return $text;
  242. }
  243.  
  244. /**
  245. * create a horizontal line insertion
  246. */
  247. protected function Write_Line() {
  248.  
  249. $x1 = $this->img_width*$this->img_scale*.15;
  250. $x2 = $this->textFinalX;
  251. $y1 = rand($this->img_height*$this->img_scale*.40, $this->img_height*$this->img_scale*.65);
  252. $y2 = rand($this->img_height*$this->img_scale*.40, $this->img_height*$this->img_scale*.65);
  253. $img_width = $this->line_Width/2*$this->img_scale;
  254.  
  255. for ($i = $img_width*-1; $i <= $img_width; $i++) {
  256. imageline($this->gd_Image, $x1, $y1+$i, $x2, $y2+$i, $this->GdFgColor);
  257. }
  258. }
  259.  
  260. /**
  261. * create a text insertion
  262. */
  263. protected function Write_Text($text, $fontcfg = array()) {
  264. if (empty($fontcfg)) {
  265. // Select the font configuration
  266. $fontcfg  = $this->fonts[array_rand($this->fonts)];
  267. }
  268.  
  269. // Full path of font file
  270. $fontfile = $this->path.'/fonts/'.$fontcfg['font'];
  271.  
  272. /** Increase font-size for shortest words: 9% for each glyp missing */
  273. $lettersMissing = $this->max_Word_Length-strlen($text);
  274. $fontSizefactor = 1+($lettersMissing*0.09);
  275.  
  276. // Text generation (char by char)
  277. $x      = 20*$this->img_scale;
  278. $y      = round(($this->img_height*27/40)*$this->img_scale);
  279. $length = strlen($text);
  280. for ($i=0; $i<$length; $i++) {
  281. $degree   = rand($this->max_rotation*-1, $this->max_rotation);
  282. $fontsize = rand($fontcfg['minSize'], $fontcfg['maxSize'])*$this->img_scale*$fontSizefactor;
  283. $letter   = substr($text, $i, 1);
  284.  
  285. if ($this->txtshadowColor) {
  286. $coords = imagettftext($this->gd_Image, $fontsize, $degree,
  287. $x+$this->img_scale, $y+$this->img_scale,
  288. $this->GdShadowColor, $fontfile, $letter);
  289. }
  290. $coords = imagettftext($this->gd_Image, $fontsize, $degree,
  291. $x, $y,
  292. $this->GdFgColor, $fontfile, $letter);
  293. $x += ($coords[2]-$x) + ($fontcfg['spacing']*$this->img_scale);
  294. }
  295.  
  296. $this->textFinalX = $x;
  297. }
  298.  
  299. /**
  300. * create a wave filter
  301. */
  302. protected function Wave_Image() {
  303. // X-axis wave generation
  304. $xp = $this->img_scale*$this->x_axis*rand(1,3);
  305. $k = rand(0, 100);
  306. for ($i = 0; $i < ($this->img_width*$this->img_scale); $i++) {
  307. imagecopy($this->gd_Image, $this->gd_Image,
  308. $i-1, sin($k+$i/$xp) * ($this->img_scale*$this->x_amplitude),
  309. $i, 0, 1, $this->img_height*$this->img_scale);
  310. }
  311.  
  312. // Y-axis wave generation
  313. $k = rand(0, 100);
  314. $yp = $this->img_scale*$this->y_axis*rand(1,2);
  315. for ($i = 0; $i < ($this->img_height*$this->img_scale); $i++) {
  316. imagecopy($this->gd_Image, $this->gd_Image,
  317. sin($k+$i/$yp) * ($this->img_scale*$this->y_amplitude), $i-1,
  318. 0, $i, $this->img_width*$this->img_scale, 1);
  319. }
  320. }
  321.  
  322. /**
  323. * set and reduce the image to the final size
  324. */
  325. protected function Reduce_Image() {
  326. // Reduzco el tamaño de la imagen
  327. $imResampled = imagecreatetruecolor($this->img_width, $this->img_height);
  328. imagecopyresampled($imResampled, $this->gd_Image,
  329. 0, 0, 0, 0,
  330. $this->img_width, $this->img_height,
  331. $this->img_width*$this->img_scale, $this->img_height*$this->img_scale
  332. );
  333. imagedestroy($this->gd_Image);
  334. $this->gd_Image = $imResampled;
  335. }
  336.  
  337. /**
  338. * create a file generation
  339. */
  340. protected function Write_Image() {
  341. if ($this->imgFormat == 'png' && function_exists('imagepng')) {
  342. header("Content-type: image/png");
  343. imagepng($this->gd_Image);
  344. } else {
  345. header("Content-type: image/jpeg");
  346. imagejpeg($this->gd_Image, null, 80);
  347. }
  348. }
  349.  
  350. /**
  351. * create the cleaning up method
  352. */
  353. protected function CleaningUp() {
  354. imagedestroy($this->gd_Image);
  355. }
  356. }
  • Second, do this following code for viewing the captcha. Name it “index.php”.
  1. <h3>Test if you are human.</h3>
  2. <div onload="document.getElementById('strcaptcha').focus()">
  3. <form action="" method="post">
  4. <img id="imgcaptcha" src="loadcaptcha.php"><br>
  5. <!-- Changing captcha -->
  6. <a href="#" onclick="LoadCaptcha()">Reload Captcha.</a><br>
  7. <br>
  8. <!-- end changing -->
  9. <input autocomplete="off" id="strcaptcha" name="strcaptcha" type=
  10. "text"><br>
  11. <input name="submit" type="submit">
  12. </form>
  • Third, create a script for refreshing the captcha.
javascript

  1. /* create a function for changing capcha */
  2. function LoadCaptcha() {
  3. document.getElementById('imgcaptcha').src = 'loadcaptcha.php?' + Math.random();
  4. document.getElementById('strcaptcha').focus();
  5. }
  • Finally, create a method for validating the captcha.
  1. /* start the session*/
  2. /** Validating captcha */
  3. if (isset($_POST['strcaptcha'])) {
  4. if (empty($_SESSION['captcha']) || trim(strtolower($_POST['strcaptcha'])) != $_SESSION['captcha']) {
  5. $msg = "Invalid captcha";
  6. $color = "background-color: #FF606C";
  7. } else {
  8. $msg = "Valid captcha";
  9. $color = "background-color: #CCFF99";
  10. }
  11. /* requesting captcha */
  12. htmlspecialchars($_POST['strcaptcha']);
  13. /* load message */
  14. echo $view = "<div id='result' style='".$color."' >
  15. <p><h2>".$msg."</h2></p>
  16. </div>";
  17. /* clearing captcha */
  18. unset($_SESSION['captcha']);
  19. }

 

For all students who need programmer for your thesis system or anyone who needs a sourcecode in any programming languages.  You can contact me @ :

 

Email – jannopalacios@gmail.com

Mobile No. – 09305235027 – tnt

Download Sourcecode

Facebook Comments

Check Your Domain Ranking

Leave a Reply

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

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!