PHP School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

PHP Source Code


Welcome to Dream.In.Code
Become a PHP Expert!

Join 306,787 PHP Programmers for FREE! Get instant access to thousands of PHP experts, tutorials, code snippets, and more! There are 1,606 people online right now. Registration is fast and FREE... Join Now!





CAPTCHA

This is a simple captcha that generates an image based on a random string stored in a database. MySQL required.

Submitted By: Styx
Actions:
Rating:
Views: 2,763

Language: PHP

Last Modified: May 2, 2007
Instructions:
Create the following SQL table:
CREATE TABLE captcha (
confirm_id char(32) DEFAULT '' NOT NULL,
session_id char(32) DEFAULT '' NOT NULL,
code char(8) DEFAULT '' NOT NULL,
PRIMARY KEY (session_id,confirm_id)
);

Modify the settings in the script.

This script uses TTF fonts to display the code. You can upload your own fonts to use. Just be sure to change $font_dir to wherever your fonts are stored. (A default font without rotation is used if none are available.)

There are two pages to this snippet. The first half is the captcha script. The second half is an example test page. Use the test page to understand how to implement the captcha.

This script originally inspired by the Anti-Spam ACP mod by EXreaction:
http://www.phpbb.com/community/viewtopic.php?t=465600

Snippet


  1. <?php
  2. //
  3. // Settings
  4. //
  5. $dbhost = 'localhost';
  6. $dbuser = 'username';
  7. $dbpass = 'password';
  8. $database = 'database';
  9.  
  10. $min_char = 4;
  11. $max_char = 8;
  12. $font_dir = './*.ttf';
  13.  
  14. //
  15. // Initial start
  16. //
  17. mysql_connect($dbhost, $dbuser, $dbpass);
  18. mysql_select_db($database);
  19.  
  20.  
  21. //
  22. // Initiate image
  23. //
  24. header("content-type: image/png");
  25. header("Cache-control: no-cache, no-store");
  26.  
  27. $width = rand(200, 300);
  28. $height = rand(50, 70);
  29. $img = imagecreate($width, $height);
  30. $background = imagecolorallocate($img, rand(200, 255), rand(200, 255), rand(200, 255));
  31.  
  32. //
  33. // Compile code
  34. //
  35. $array = array();
  36. for ($i = 0; $i < $max_char; $i++)
  37. {
  38.   $alpha = chr(rand(1, 26) + 64);
  39.   $numeric = rand(0, 9);
  40.  
  41.   $array[] = (rand(0, 1) == 0 || count($array) < $min_char) ? ((rand(0, 1) == 0) ? $alpha : $numeric) : '';
  42. }
  43.  
  44. $code = str_replace('0', 'Z', implode('', $array));
  45.  
  46. //
  47. // Query database
  48. //
  49. $confirm_id = (eregi('^[a-z0-9]{32}$', $_GET['id'])) ? $_GET['id'] : md5(uniqid($_SERVER['REMOTE_ADDR']));
  50. $session_id = (eregi("^[a-z0-9]{32}$", session_id())) ? session_id() : '';
  51. mysql_query("DELETE FROM captcha WHERE session_id = '$session_id'");
  52. mysql_query("INSERT INTO captcha (confirm_id, session_id, code) VALUES ('$confirm_id', '$session_id', '$code')");
  53.  
  54. //
  55. // Create background
  56. //
  57. for ($i = 0; $i < rand(5, 20); $i++)
  58. {
  59.   $color = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
  60.   $loc_x = rand(-100, $width + 100);
  61.   $loc_y = rand(-50, $height + 50);
  62.   $end_x = rand(-100, $width + 100);
  63.   $end_y = rand(-50, $height + 50);
  64.  
  65.   // Background shapes
  66.   $shape = rand(1, 3);
  67.   switch ($shape)
  68.   {
  69.     case 1:
  70.       // Draw an ellipse
  71.       imageellipse($img, $loc_x, $loc_y, rand(100, 400), rand(50, 400), $color);
  72.     break;
  73.  
  74.     case 2:
  75.       // Draw a rectangle
  76.       imagerectangle($img, $loc_x, $loc_y, $end_x, $end_y, $color);
  77.     break;
  78.  
  79.     case 3:
  80.       // Draw a line
  81.       imageline($img, $loc_x, $loc_y, $end_x, $end_y, $color);
  82.     break;
  83.   }
  84. }
  85.  
  86. //
  87. // Compile image
  88. //
  89. $x_move = $width / (strlen($code) + 1);
  90. $current_pos = rand(0, $x_move / 2);
  91.  
  92. $less_rotate = array('N', 'Z', '6', '9');
  93. for ($i = 0; $i < strlen($code); $i++)
  94. {
  95.   $size = rand(15, 20);
  96.   $angle = (in_array($code[$i], $less_rotate)) ? rand(-15, 15) : rand(-30, 30);
  97.  
  98.   $x_pos = $current_pos + rand($size + 1, $x_move);
  99.   $y_pos = $height/2 + rand(-8, 8);
  100.   $current_pos = $x_pos;
  101.  
  102.   $fonts = glob($font_dir);
  103.   $font = $fonts[array_rand($fonts)];
  104.   $color = imagecolorallocate($img, rand(0, 127), rand(0, 127), rand(0, 127));
  105.  
  106.   if (!empty($font))
  107.     imagettftext($img, $size, $angle, $x_pos, $y_pos, $color, $font, $code[$i]);
  108.   else
  109.     imagestring($img, 5, $x_pos, $y_pos, $code[$i], $color);
  110. }
  111.  
  112. //
  113. // Create image
  114. //
  115. imagepng($img);
  116. imagedestroy($img);
  117.  
  118.  
  119. /* ------ MySQL Query ------
  120. CREATE TABLE captcha (
  121. confirm_id char(32) DEFAULT '' NOT NULL,
  122. session_id char(32) DEFAULT '' NOT NULL,
  123. code char(8) DEFAULT '' NOT NULL,
  124. PRIMARY KEY  (session_id,confirm_id)
  125. );
  126. */
  127. ?>
  128.  
  129. ### TEST PAGE ###
  130. <?php
  131. mysql_connect('localhost', 'username', 'password');
  132. mysql_select_db('database');
  133.  
  134.  
  135. if (isset($_POST['submit']))
  136. {
  137.   $confirm_id = (eregi('^[a-z0-9]{32}$', $_POST['confirm_id'])) ? $_POST['confirm_id'] : '';
  138.   $result = mysql_query("SELECT * FROM captcha WHERE confirm_id = '$confirm_id' LIMIT 1");
  139.   $row = mysql_fetch_assoc($result);
  140.  
  141.   if (!$row || $_POST['confirm'] !== $row['code'])
  142.   {
  143.     echo '<b>Invalid Code:</b>';
  144.   }
  145.   else
  146.   {
  147.     $session_id = (eregi("^[a-z0-9]{32}$", session_id())) ? session_id() : '';
  148.     mysql_query("DELETE FROM captcha WHERE session_id = '$session_id'");
  149.  
  150.     echo '<b>Valid:</b>';
  151.   }
  152.  
  153.   echo $_POST['confirm'] . '|' . $row['code'] . '<br />';
  154. }
  155.  
  156. $confirm_id = md5(uniqid($_SERVER['REMOTE_ADDR']));
  157.  
  158. ?>
  159. <img src="captcha.php?id=<?php echo $confirm_id; ?>">
  160. <form method="post">
  161. <input type="hidden" name="confirm_id" value="<?php echo $confirm_id; ?>">
  162. <input type="text" name="confirm" size="30">
  163. <input type="submit" name="submit" value="Submit">
  164. </form>

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live PHP Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

PHP Tutorials

Reference Sheets

PHP Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month