captcha.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. if (!isset($_SESSION)) {
  3. session_start();
  4. } //檢查SESSION是否啟動
  5. $_SESSION['check_word'] = ''; //設置存放檢查碼的SESSION
  6. //設置定義為圖片
  7. header("Content-type: image/PNG");
  8. /*
  9. imgcode($nums,$width,$high)
  10. 設置產生驗證碼圖示的參數
  11. $nums 生成驗證碼個數
  12. $width 圖片寬
  13. $high 圖片高
  14. */
  15. imgcode(5, 120, 30);
  16. //imgcode的function
  17. function imgcode($nums, $width, $high)
  18. {
  19. //去除了數字0和1 字母小寫O和L,為了避免辨識不清楚
  20. //$str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMOPQRSTUBWXYZ";
  21. $str = "1234567890";
  22. $code = '';
  23. for ($i = 0; $i < $nums; $i++) {
  24. $code .= $str[mt_rand(0, strlen($str) - 1)];
  25. }
  26. $_SESSION['check_word'] = $code;
  27. //建立圖示,設置寬度及高度與顏色等等條件
  28. $image = imagecreate($width, $high);
  29. $black = imagecolorallocate($image, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200));
  30. $border_color = imagecolorallocate($image, 21, 106, 235);
  31. $background_color = imagecolorallocate($image, 235, 236, 237);
  32. //建立圖示背景
  33. imagefilledrectangle($image, 0, 0, $width, $high, $background_color);
  34. //建立圖示邊框
  35. imagerectangle($image, 0, 0, $width - 1, $high - 1, $border_color);
  36. //在圖示布上隨機產生大量躁點
  37. for ($i = 0; $i < 80; $i++) {
  38. imagesetpixel($image, rand(0, $width), rand(0, $high), $black);
  39. }
  40. $strx = rand(3, 8);
  41. for ($i = 0; $i < $nums; $i++) {
  42. $strpos = rand(1, 6);
  43. imagestring($image, 5, $strx, $strpos, substr($code, $i, 1), $black);
  44. $strx += rand(10, 30);
  45. }
  46. imagepng($image);
  47. imagedestroy($image);
  48. }