Captcha with color protection


/ Published in: PHP
Save to your folder(s)

Tell the users to enter only the red or only the blue digits, not everything they see.
Most bots will try to enter everything, displayed on the images.
To check is captcha code entered correctly, use $_SESSION['captcha']['red'] to check the red digits only and $_SESSION['captcha']['blue'] to check the blue digits only. Good luck !


Copy this code and paste it in your HTML
  1. header("Content-type: image/png");
  2. $width = 146;
  3. $height = 30;
  4.  
  5. $im = @imagecreate($width, $height)or die("Cannot Initialize new GD image stream");
  6.  
  7. imagecolorallocate($im, 255, 250, 255);
  8. $noise_color = imagecolorallocate($im, 207, 239, 250);
  9. for($i=0; $i<($width*$height)/3; $i++) {
  10. imagefilledellipse($im, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
  11. }
  12.  
  13. /* generate random lines in background */
  14. for($i=0; $i<($width*$height)/150; $i++ ) {
  15. imageline($im, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
  16. }
  17.  
  18. $text_color[0] = imagecolorallocate($im, 255, 0, 0);
  19. $text_color[1] = imagecolorallocate($im, 51, 166, 207);
  20.  
  21. $text = mb_substr(uniqid(mt_rand(), true), 0, 6);
  22. unset($_SESSION['captcha']);
  23. $_SESSION['captcha']['blue'] = $_SESSION['captcha']['red'] = '';
  24.  
  25. for($j = 0; $j < mb_strlen($text); $j++) {
  26. imagettftext($im, 20, 0, 5+($j*23), 24, $text_color[$j%2], './offshore.ttf', $text[$j]);
  27. if(($j%2) == 1) {
  28. $_SESSION['captcha']['blue'] .= $text[$j];
  29. }
  30. else {
  31. $_SESSION['captcha']['red'] .= $text[$j];
  32. }
  33. }
  34. imagepng($im);

URL: http://vladimir-ivanov.net

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.