php简单生成验证码

利用php自身带的函数来实现图片验证码生成功能,php简单生成验证码实例代码如下:

  1. <?php
  2. //must start or continue session and save CAPTCHA string in $_SESSION for
  3. //it to be available to other requests
  4. if(!isset($_SESSION)){
  5. session_start();
  6. header('Cache-control:private');
  7. }
  8. //create a 65*20 pixel image
  9. $width=65;
  10. $height=20;
  11. $image=imagecreate(65,20);
  12. //fill the image background color
  13. $bg_color=imagecolorallocate($image,0x33,0x66,0xFF);
  14. imagefilledrectangle($image,0,0,$width,$height,$bg_color);
  15. //fetch random text
  16. $text=random_text(5);
  17. //determine x and y coordinates for centering text
  18. $font=5;
  19. $x=imagesx($image)/2-strlen($text)*imagefontwidth($font)/2;
  20. $y=imagesy($image)/2-imagefontheight($font)/2;
  21. //write text on image //开源代码phpfensi.com
  22. $fg_color=imagecolorallocate($image,0xFF,0xFF,0xFF);
  23. imagestring($image,$font,$x,$y,$text,$fg_color);
  24. //save the CAPTCHA string for later comparison
  25. $_SESSION['captcha']=$text;
  26. //output the image
  27. header('Content-type:image/png');
  28. imagepng($image);
  29. imagedestroy($image);
  30. ?>