php生成验证码实现代码

一款php生成验证码实现代码,自定义了session的目录,这样就不是php.ini里默认的session文件保存路径了,如下面session_save_path,可重新定义目录.

session_save_path,可重新定义目录,php生成验证码实现代码如下:

  1. $sesssavepath = dirname(__file__)."/../data/sessions/";
  2. if(is_writeable($sesssavepath) && is_readable($sesssavepath)){ session_save_path($sesssavepath); }
  3. session_start();
  4. $vstr = '';
  5. for($i=0; $i<4; $i++) $vstr .= chr(mt_rand(65,90));
  6. if(function_exists("imagecreate")){
  7. $ntime = time();
  8. if(emptyempty($_session['verifycode_last']) || emptyempty($_session['verifycode']) || ($ntime - $_session['verifycode_last'] > 5)){
  9. $_session['verifycode'] = strtolower($vstr);
  10. $_session['verifycode_last'] = $ntime;
  11. }
  12. $vstr = $_session['verifycode'];
  13. $vstrlen = strlen($vstr);
  14. $img = imagecreate(50,20);
  15. imagecolorallocate($img, 255,255,255);
  16. $line1 = imagecolorallocate($img,240,220,180);
  17. $line2 = imagecolorallocate($img,250,250,170);
  18. for($j=3;$j<=16;$j=$j+3){
  19. imageline($img,2,$j,48,$j,$line1);
  20. }
  21. for($j=2;$j<52;$j=$j+(mt_rand(3,6))){
  22. imageline($img,$j,2,$j-6,18,$line2);
  23. }
  24. $bordercolor = imagecolorallocate($img, 0x99,0x99,0x99);
  25. imagerectangle($img, 0, 0, 49, 19, $bordercolor);
  26. $fontcolor = imagecolorallocate($img, 48,61,50);
  27. for($i=0;$i<$vstrlen;$i++){
  28. $bc = mt_rand(0,1);
  29. $vstr[$i] = strtoupper($vstr[$i]);
  30. imagestring($img, 5, $i*10+6, mt_rand(2,4), $vstr[$i], $fontcolor);
  31. }
  32. header("pragma:no-cachern");
  33. header("cache-control:no-cachern");
  34. header("expires:0rn");
  35. if(function_exists("imagejpeg")){
  36. header("content-type:image/jpegrn");
  37. imagejpeg($img);
  38. }else{
  39. header("content-type:image/pngrn");
  40. imagepng($img);
  41. }
  42. imagedestroy($img);
  43. exit();//开源代码phpfensi.com
  44. }