captcha.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. $code = '';
  22. for ($i = 0; $i < $nums; $i++) {
  23. $code .= $str[mt_rand(0, strlen($str) - 1)];
  24. }
  25. $_SESSION['check_word'] = $code;
  26. //建立圖示,設置寬度及高度與顏色等等條件
  27. $image = imagecreate($width, $high);
  28. $black = imagecolorallocate($image, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200));
  29. $border_color = imagecolorallocate($image, 21, 106, 235);
  30. $background_color = imagecolorallocate($image, 235, 236, 237);
  31. //建立圖示背景
  32. imagefilledrectangle($image, 0, 0, $width, $high, $background_color);
  33. //建立圖示邊框
  34. imagerectangle($image, 0, 0, $width - 1, $high - 1, $border_color);
  35. //在圖示布上隨機產生大量躁點
  36. for ($i = 0; $i < 80; $i++) {
  37. imagesetpixel($image, rand(0, $width), rand(0, $high), $black);
  38. }
  39. $strx = rand(3, 8);
  40. for ($i = 0; $i < $nums; $i++) {
  41. $strpos = rand(1, 6);
  42. imagestring($image, 5, $strx, $strpos, substr($code, $i, 1), $black);
  43. $strx += rand(10, 30);
  44. }
  45. imagepng($image);
  46. imagedestroy($image);
  47. }