4 * Project: Securimage: A PHP class for creating and managing form CAPTCHA images<br />
5 * File: securimage.php<br />
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or any later version.<br /><br />
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.<br /><br />
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA<br /><br />
21 * Any modifications to the library should be indicated clearly in the source code
22 * to inform users that the changes are not a part of the original software.<br /><br />
24 * If you found this script useful, please take a quick moment to rate it.<br />
25 * http://www.hotscripts.com/rate/49400.html Thanks.
27 * @link http://www.phpcaptcha.org Securimage PHP CAPTCHA
28 * @link http://www.phpcaptcha.org/latest.zip Download Latest Version
29 * @link http://www.phpcaptcha.org/Securimage_Docs/ Online Documentation
30 * @copyright 2007 Drew Phillips
31 * @author drew010 <drew@drew-phillips.com>
32 * @version 1.0.3.1 (March 24, 2008)
41 - Error reading from wordlist in some cases caused words to be cut off 1 letter short
44 - Removed shadow_text from code which could cause an undefined property error due to removal from previous version
47 - Audible CAPTCHA Code wav files
48 - Create codes from a word list instead of random strings
51 - Added the ability to use a selected character set, rather than a-z0-9 only.
52 - Added the multi-color text option to use different colors for each letter.
53 - Switched to automatic session handling instead of using files for code storage
54 - Added GD Font support if ttf support is not available. Can use internal GD fonts or load new ones.
55 - Added the ability to set line thickness
56 - Added option for drawing arced lines over letters
57 - Added ability to choose image type for output
62 * Output images in JPEG format
64 define('SI_IMAGE_JPEG', 1);
66 * Output images in PNG format
68 define('SI_IMAGE_PNG', 2);
70 * Output images in GIF format
71 * Must have GD >= 2.0.28!
73 define('SI_IMAGE_GIF', 3);
76 * Securimage CAPTCHA Class.
85 * The desired width of the CAPTCHA image.
89 var $image_width = 175;
92 * The desired width of the CAPTCHA image.
96 var $image_height = 45;
99 * The image format for output.<br />
100 * Valid options: SI_IMAGE_PNG, SI_IMAGE_JPG, SI_IMAGE_GIF
104 var $image_type = SI_IMAGE_PNG;
107 * The length of the code to generate.
111 var $code_length = 4;
114 * The character set for individual characters in the image.<br />
115 * Letters are converted to uppercase.<br />
116 * The font must support the letters or there may be problematic substitutions.
120 var $charset = 'ABCDEFGHKLMNPRSTUVWYZ23456789';
121 //var $charset = '0123456789';
124 * Create codes using this word list
126 * @var string The path to the word list to use for creating CAPTCHA codes
128 var $wordlist_file = '../words/words.txt';
131 * True to use a word list file instead of a random code
135 var $use_wordlist = true;
138 * Whether to use a GD font instead of a TTF font.<br />
139 * TTF offers more support and options, but use this if your PHP doesn't support TTF.<br />
143 var $use_gd_font = false;
146 * The GD font to use.<br />
147 * Internal gd fonts can be loaded by their number.<br />
148 * Alternatively, a file path can be given and the font will be loaded from file.
152 var $gd_font_file = 'gdfonts/bubblebath.gdf';
155 * The approximate size of the font in pixels.<br />
156 * This does not control the size of the font because that is determined by the GD font itself.<br />
157 * This is used to aid the calculations of positioning used by this class.<br />
161 var $gd_font_size = 20;
163 // Note: These font options below do not apply if you set $use_gd_font to true with the exception of $text_color
166 * The path to the TTF font file to load.
170 var $ttf_file = "./elephant.ttf";
173 * The font size.<br />
174 * Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2)<br />
181 * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
182 * Higher values represent a counter-clockwise rotation.<br />
183 * For example, a value of 90 would result in bottom-to-top reading text.
187 var $text_angle_minimum = -20;
190 * The minimum angle in degrees, with 0 degrees being left-to-right reading text.<br />
191 * Higher values represent a counter-clockwise rotation.<br />
192 * For example, a value of 90 would result in bottom-to-top reading text.
196 var $text_angle_maximum = 20;
199 * The X-Position on the image where letter drawing will begin.<br />
200 * This value is in pixels from the left side of the image.
204 var $text_x_start = 8;
207 * Letters can be spaced apart at random distances.<br />
208 * This is the minimum distance between two letters.<br />
209 * This should be <i>at least</i> as wide as a font character.<br />
210 * Small values can cause letters to be drawn over eachother.<br />
214 var $text_minimum_distance = 30;
217 * Letters can be spaced apart at random distances.<br />
218 * This is the maximum distance between two letters.<br />
219 * This should be <i>at least</i> as wide as a font character.<br />
220 * Small values can cause letters to be drawn over eachother.<br />
224 var $text_maximum_distance = 33;
227 * The background color for the image.<br />
228 * This should be specified in HTML hex format.<br />
229 * Make sure to include the preceding # sign!
233 var $image_bg_color = "#e3daed";
236 * The text color to use for drawing characters.<br />
237 * This value is ignored if $use_multi_text is set to true.<br />
238 * Make sure this contrasts well with the background color.<br />
239 * Specify the color in HTML hex format with preceding # sign
241 * @see Securimage::$use_multi_text
244 var $text_color = "#ff0000";
247 * Set to true to use multiple colors for each character.
249 * @see Securimage::$multi_text_color
252 var $use_multi_text = true;
255 * String of HTML hex colors to use.<br />
256 * Separate each possible color with commas.<br />
257 * Be sure to precede each value with the # sign.
261 var $multi_text_color = "#0a68dd,#f65c47,#8d32fd";
264 * Set to true to make the characters appear transparent.
266 * @see Securimage::$text_transparency_percentage
269 var $use_transparent_text = true;
272 * The percentage of transparency, 0 to 100.<br />
273 * A value of 0 is completely opaque, 100 is completely transparent (invisble)
275 * @see Securimage::$use_transparent_text
278 var $text_transparency_percentage = 15;
283 * Draw vertical and horizontal lines on the image.
285 * @see Securimage::$line_color
286 * @see Securimage::$line_distance
287 * @see Securimage::$line_thickness
288 * @see Securimage::$draw_lines_over_text
291 var $draw_lines = true;
294 * The color of the lines drawn on the image.<br />
295 * Use HTML hex format with preceding # sign.
297 * @see Securimage::$draw_lines
300 var $line_color = "#80BFFF";
303 * How far apart to space the lines from eachother in pixels.
305 * @see Securimage::$draw_lines
308 var $line_distance = 5;
311 * How thick to draw the lines in pixels.<br />
312 * 1-3 is ideal depending on distance
314 * @see Securimage::$draw_lines
315 * @see Securimage::$line_distance
318 var $line_thickness = 1;
321 * Set to true to draw angled lines on the image in addition to the horizontal and vertical lines.
323 * @see Securimage::$draw_lines
326 var $draw_angled_lines = false;
329 * Draw the lines over the text.<br />
330 * If fales lines will be drawn before putting the text on the image.<br />
331 * This can make the image hard for humans to read depending on the line thickness and distance.
335 var $draw_lines_over_text = false;
338 * For added security, it is a good idea to draw arced lines over the letters to make it harder for bots to segment the letters.<br />
339 * Two arced lines will be drawn over the text on each side of the image.<br />
340 * This is currently expirimental and may be off in certain configurations.
344 var $arc_linethrough = true;
347 * The colors or color of the arced lines.<br />
348 * Use HTML hex notation with preceding # sign, and separate each value with a comma.<br />
349 * This should be similar to your font color for single color images.
353 var $arc_line_colors = "#8080ff";
356 * Full path to the WAV files to use to make the audio files, include trailing /.<br />
357 * Name Files [A-Z0-9].wav
362 var $audio_path = './audio/';
365 //END USER CONFIGURATION
366 //There should be no need to edit below unless you really know what you are doing.
369 * The gd image resource.
377 * The background image resource
385 * The code generated by the script
393 * The code that was entered by the user
401 * Whether or not the correct code was entered
409 * Class constructor.<br />
410 * Because the class uses sessions, this will attempt to start a session if there is no previous one.<br />
411 * If you do not start a session before calling the class, the constructor must be called before any
412 * output is sent to the browser.
415 * $securimage = new Securimage();
419 function Securimage()
421 if ( session_id() == '' ) { // no session has been started yet, which is needed for validation
427 * Generate a code and output the image to the browser.
431 * include 'securimage.php';
432 * $securimage = new Securimage();
433 * $securimage->show('bg.jpg');
437 * @param string $background_image The path to an image to use as the background for the CAPTCHA
439 function show($background_image = "")
441 if($background_image != "" && is_readable($background_image)) {
442 $this->bgimg = $background_image;
449 * Validate the code entered by the user.
452 * $code = $_POST['code'];
453 * if ($securimage->check($code) == false) {
454 * die("Sorry, the code entered did not match.");
459 * @param string $code The code the user entered
460 * @return boolean true if the code was correct, false if not
462 function check($code)
464 $this->code_entered = $code;
466 return $this->correct_code;
470 * Generate and output the image
477 if($this->use_transparent_text == true || $this->bgimg != "") {
478 $this->im = imagecreatetruecolor($this->image_width, $this->image_height);
479 $bgcolor = imagecolorallocate($this->im, hexdec(substr($this->image_bg_color, 1, 2)), hexdec(substr($this->image_bg_color, 3, 2)), hexdec(substr($this->image_bg_color, 5, 2)));
480 imagefilledrectangle($this->im, 0, 0, imagesx($this->im), imagesy($this->im), $bgcolor);
481 } else { //no transparency
482 $this->im = imagecreate($this->image_width, $this->image_height);
483 $bgcolor = imagecolorallocate($this->im, hexdec(substr($this->image_bg_color, 1, 2)), hexdec(substr($this->image_bg_color, 3, 2)), hexdec(substr($this->image_bg_color, 5, 2)));
486 if($this->bgimg != "") { $this->setBackground(); }
490 if (!$this->draw_lines_over_text && $this->draw_lines) $this->drawLines();
494 if ($this->arc_linethrough == true) $this->arcLines();
496 if ($this->draw_lines_over_text && $this->draw_lines) $this->drawLines();
503 * Set the background of the CAPTCHA image
508 function setBackground()
510 $dat = @getimagesize($this->bgimg);
511 if($dat == false) { return; }
514 case 1: $newim = @imagecreatefromgif($this->bgimg); break;
515 case 2: $newim = @imagecreatefromjpeg($this->bgimg); break;
516 case 3: $newim = @imagecreatefrompng($this->bgimg); break;
517 case 15: $newim = @imagecreatefromwbmp($this->bgimg); break;
518 case 16: $newim = @imagecreatefromxbm($this->bgimg); break;
524 imagecopy($this->im, $newim, 0, 0, 0, 0, $this->image_width, $this->image_height);
528 * Draw arced lines over the text
535 $colors = explode(',', $this->randomColor());
536 imagesetthickness($this->im, 3);
538 $color = $colors[rand(0, sizeof($colors) - 1)];
539 $linecolor = imagecolorallocate($this->im, hexdec(substr($color, 1, 2)), hexdec(substr($color, 3, 2)), hexdec(substr($color, 5, 2)));
541 $xpos = $this->text_x_start + ($this->font_size * 2) + rand(-5, 5);
542 $width = $this->image_width / 2.66 + rand(3, 10);
543 $height = $this->font_size * 2.14 - rand(3, 10);
545 if ( rand(0,100) % 2 == 0 ) {
547 $ypos = $this->image_height / 2 - rand(5, 15);
548 $xpos += rand(5, 15);
550 $start = rand(180, 246);
551 $ypos = $this->image_height / 2 + rand(5, 15);
554 $end = $start + rand(75, 110);
556 imagearc($this->im, $xpos, $ypos, $width, $height, $start, $end, $linecolor);
558 $color = $colors[rand(0, sizeof($colors) - 1)];
559 $linecolor = imagecolorallocate($this->im, hexdec(substr($color, 1, 2)), hexdec(substr($color, 3, 2)), hexdec(substr($color, 5, 2)));
561 if ( rand(1,75) % 2 == 0 ) {
562 $start = rand(45, 111);
563 $ypos = $this->image_height / 2 - rand(5, 15);
564 $xpos += rand(5, 15);
566 $start = rand(200, 250);
567 $ypos = $this->image_height / 2 + rand(5, 15);
570 $end = $start + rand(75, 100);
572 imagearc($this->im, $this->image_width * .75, $ypos, $width, $height, $start, $end, $linecolor);
576 * Draw lines on the image
583 $linecolor = imagecolorallocate($this->im, hexdec(substr($this->line_color, 1, 2)), hexdec(substr($this->line_color, 3, 2)), hexdec(substr($this->line_color, 5, 2)));
584 imagesetthickness($this->im, $this->line_thickness);
587 for($x = 1; $x < $this->image_width; $x += $this->line_distance) {
588 imageline($this->im, $x, 0, $x, $this->image_height, $linecolor);
592 for($y = 11; $y < $this->image_height; $y += $this->line_distance) {
593 imageline($this->im, 0, $y, $this->image_width, $y, $linecolor);
596 if ($this->draw_angled_lines == true) {
597 for ($x = -($this->image_height); $x < $this->image_width; $x += $this->line_distance) {
598 imageline($this->im, $x, 0, $x + $this->image_height, $this->image_height, $linecolor);
601 for ($x = $this->image_width + $this->image_height; $x > 0; $x -= $this->line_distance) {
602 imageline($this->im, $x, 0, $x - $this->image_height, $this->image_height, $linecolor);
608 * Draw the CAPTCHA code over the image
615 if ($this->use_gd_font == true) {
616 if (!is_int($this->gd_font_file)) { //is a file name
617 $font = @imageloadfont($this->gd_font_file);
618 if ($font == false) {
619 trigger_error("Failed to load GD Font file {$this->gd_font_file} ", E_USER_WARNING);
622 } else { //gd font identifier
623 $font = $this->gd_font_file;
626 $color = imagecolorallocate($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)));
627 imagestring($this->im, $font, $this->text_x_start, ($this->image_height / 2) - ($this->gd_font_size / 2), $this->code, $color);
630 if($this->use_transparent_text == true) {
631 $alpha = intval($this->text_transparency_percentage / 100 * 127);
632 $font_color = imagecolorallocatealpha($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)), $alpha);
633 } else { //no transparency
634 $font_color = imagecolorallocate($this->im, hexdec(substr($this->text_color, 1, 2)), hexdec(substr($this->text_color, 3, 2)), hexdec(substr($this->text_color, 5, 2)));
637 $x = $this->text_x_start;
638 $strlen = strlen($this->code);
639 $y_min = ($this->image_height / 2) + ($this->font_size / 2) - 2;
640 $y_max = ($this->image_height / 2) + ($this->font_size / 2) + 2;
641 $colors = explode(',', $this->multi_text_color);
643 for($i = 0; $i < $strlen; ++$i) {
644 $angle = rand($this->text_angle_minimum, $this->text_angle_maximum);
645 $y = rand($y_min, $y_max);
646 if ($this->use_multi_text == true) {
647 $idx = rand(0, sizeof($colors) - 1);
648 $r = substr($colors[$idx], 1, 2);
649 $g = substr($colors[$idx], 3, 2);
650 $b = substr($colors[$idx], 5, 2);
651 if($this->use_transparent_text == true) {
652 $font_color = imagecolorallocatealpha($this->im, "0x$r", "0x$g", "0x$b", $alpha);
654 $font_color = imagecolorallocate($this->im, "0x$r", "0x$g", "0x$b");
657 /* Will check if the FreeType library is loaded, if not, use the default PHP fonts.
658 * @customized by ATutor, Harris Wong
660 if (function_exists('imagettftext')) {
661 @imagettftext($this->im, $this->font_size, $angle, $x, $y, $font_color, $this->ttf_file, $this->code{$i});
663 $this->arc_linethrough = false; //no arcline then,too hard to see with the built in fonts and limited size
664 imagestring($this->im, 5, $x, $y-15, $this->code{$i}, $font_color);
667 $x += rand($this->text_minimum_distance, $this->text_maximum_distance);
673 * Create a code and save to the session
678 function createCode()
682 if ($this->use_wordlist && is_readable($this->wordlist_file)) {
683 $this->code = $this->readCodeFromFile();
686 if ($this->code == false) {
687 $this->code = $this->generateCode($this->code_length);
697 * @param int $len The code length
700 function generateCode($len)
704 for($i = 1, $cslen = strlen($this->charset); $i <= $len; ++$i) {
705 $code .= strtoupper( $this->charset{rand(0, $cslen - 1)} );
711 * Reads a word list file to get a code
715 * @return mixed false on failure, a word on success
717 function readCodeFromFile()
719 $fp = @fopen($this->wordlist_file, 'rb');
720 if (!$fp) return false;
722 $fsize = filesize($this->wordlist_file);
723 if ($fsize < 32) return false; // too small of a list to be effective
726 $max = $fsize; // still pretty small but changes the range of seeking
731 fseek($fp, rand(0, $fsize - $max), SEEK_SET);
732 $data = fread($fp, 128); // read a random 128 bytes from file
734 $data = preg_replace("/\r?\n/", "\n", $data);
736 $start = strpos($data, "\n", rand(0, 100)) + 1; // random start position
737 $end = strpos($data, "\n", $start); // find end of word
739 return strtolower(substr($data, $start, $end - $start)); // return substring in 128 bytes
743 * Output image to the browser
750 header("Expires: Sun, 1 Jan 2000 12:00:00 GMT");
751 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
752 header("Cache-Control: no-store, no-cache, must-revalidate");
753 header("Cache-Control: post-check=0, pre-check=0", false);
754 header("Pragma: no-cache");
756 switch($this->image_type)
759 header("Content-Type: image/jpeg");
760 imagejpeg($this->im, null, 90);
764 header("Content-Type: image/gif");
769 header("Content-Type: image/png");
774 imagedestroy($this->im);
778 * Get WAV file data of the spoken code.<br />
779 * This is appropriate for output to the browser as audio/x-wav
782 * @return string WAV data
785 function getAudibleCode()
788 $code = $this->getCode();
792 $code = $this->getCode();
795 for($i = 0; $i < strlen($code); ++$i) {
796 $letters[] = $code{$i};
799 return $this->generateWAV($letters);
803 * Save the code in the session
810 $_SESSION['securimage_code_value'] = strtolower($this->code);
814 * Validate the code to the user code
821 if ( isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value']) ) {
822 if ( $_SESSION['securimage_code_value'] == strtolower(trim($this->code_entered)) ) {
823 $this->correct_code = true;
824 $_SESSION['securimage_code_value'] = '';
826 $this->correct_code = false;
829 $this->correct_code = false;
834 * Get the captcha code
841 if (isset($_SESSION['securimage_code_value']) && !empty($_SESSION['securimage_code_value'])) {
842 return $_SESSION['securimage_code_value'];
849 * Check if the user entered code was correct
856 return $this->correct_code;
860 * Generate a wav file by concatenating individual files
863 * @param array $letters Array of letters to build a file from
864 * @return string WAV file data
866 function generateWAV($letters)
868 $first = true; // use first file to write the header...
873 foreach ($letters as $letter) {
874 $filename = $this->audio_path . strtoupper($letter) . '.wav';
876 $fp = fopen($filename, 'rb');
880 $data = fread($fp, filesize($filename)); // read file in
882 $header = substr($data, 0, 36);
883 $body = substr($data, 44);
886 $data = unpack('NChunkID/VChunkSize/NFormat/NSubChunk1ID/VSubChunk1Size/vAudioFormat/vNumChannels/VSampleRate/VByteRate/vBlockAlign/vBitsPerSample', $header);
888 $file['sub_chunk1_id'] = $data['SubChunk1ID'];
889 $file['bits_per_sample'] = $data['BitsPerSample'];
890 $file['channels'] = $data['NumChannels'];
891 $file['format'] = $data['AudioFormat'];
892 $file['sample_rate'] = $data['SampleRate'];
893 $file['size'] = $data['ChunkSize'] + 8;
894 $file['data'] = $body;
896 if ( ($p = strpos($file['data'], 'LIST')) !== false) {
897 // If the LIST data is not at the end of the file, this will probably break your sound file
898 $info = substr($file['data'], $p + 4, 8);
899 $data = unpack('Vlength/Vjunk', $info);
900 $file['data'] = substr($file['data'], 0, $p);
901 $file['size'] = $file['size'] - (strlen($file['data']) - $p);
909 $data_len += strlen($file['data']);
915 for($i = 0; $i < sizeof($files); ++$i) {
916 if ($i == 0) { // output header
917 $out_data .= pack('C4VC8', ord('R'), ord('I'), ord('F'), ord('F'), $data_len + 36, ord('W'), ord('A'), ord('V'), ord('E'), ord('f'), ord('m'), ord('t'), ord(' '));
919 $out_data .= pack('VvvVVvv',
921 $files[$i]['format'],
922 $files[$i]['channels'],
923 $files[$i]['sample_rate'],
924 $files[$i]['sample_rate'] * (($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8),
925 ($files[$i]['bits_per_sample'] * $files[$i]['channels']) / 8,
926 $files[$i]['bits_per_sample'] );
928 $out_data .= pack('C4', ord('d'), ord('a'), ord('t'), ord('a'));
930 $out_data .= pack('V', $data_len);
933 $out_data .= $files[$i]['data'];
941 * Random color generation
942 * @return a 6 digits color code string
944 function randomColor(){
947 $str .= rand(0, 255);
952 } /* class Securimage */