php生成驗證碼函數

php生成驗證碼的函數,實用靠譜。先上下生成的驗證碼的效果圖(這裏生成的是全數字的驗證碼的示例效果):php

 php生成驗證碼函數

下面是php生成驗證碼的源碼:html

  1. <?php 
  2. session_start(); 
  3. //session_register('CheckCode');  
  4. //PHP4.2以上版本不須要用session_register()註冊SESSION變量 
  5. $type='gif'
  6. $width= 45; 
  7. $height= 20; 
  8. header("Content-type: image/".$type); 
  9. srand((double)microtime()*1000000); 
  10. if(isset($_GET['action'])){ 
  11.     $randval=randStr(4,$_GET['action']);     
  12. }else
  13.     $randval=randStr(4,'');  
  14. if($type!='gif'&&function_exists('imagecreatetruecolor')){ 
  15.     $im=@imagecreatetruecolor($width,$height); 
  16. }else
  17.     $im=@imagecreate($width,$height); 
  18. $r=Array(225,211,255,223); 
  19. $g=Array(225,236,237,215); 
  20. $b=Array(225,236,166,125); 
  21. $key=rand(0,3); 
  22. $backColor=ImageColorAllocate($im,$r[$key],$g[$key],$b[$key]);//背景色(隨機) 
  23. $borderColor=ImageColorAllocate($im,127,157,185);//邊框色 
  24. $pointColor=ImageColorAllocate($im,255,170,255);//點顏色 
  25. @imagefilledrectangle($im,0,0,$width - 1,$height - 1,$backColor);//背景位置 
  26. @imagerectangle($im,0,0,$width-1,$height-1,$borderColor); //邊框位置 
  27. $stringColor=ImageColorAllocate($im,255,51,153); 
  28. for($i=0;$i<=100;$i++){ 
  29.     $pointX=rand(2,$width-2); 
  30.     $pointY=rand(2,$height-2); 
  31.     @imagesetpixel($im,$pointX,$pointY,$pointColor); 
  32. @imagestring($im,5,5,1,$randval,$stringColor); 
  33. $ImageFun='Image'.$type
  34. $ImageFun($im); 
  35. @imagedestroy($im); 
  36. $_SESSION['CheckCode']=$randval
  37. function randStr($len=6,$format='ALL'){ 
  38.     switch($format){ 
  39.         case 'ALL'://生成包含數字和字母的驗證碼 
  40.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'break
  41.         case 'CHAR'://僅生成包含字母的驗證碼 
  42.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'break
  43.         case 'NUMBER'://僅生成包含數字的驗證碼 
  44.             $chars='0123456789'break
  45.         default : 
  46.             $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'break
  47.     } 
  48.     $string=''
  49.     while(strlen($string)<$len
  50.     $string.=substr($chars,(mt_rand()%strlen($chars)),1); 
  51.     return $string

該函數的具體使用方法請看以下這個示例(這裏是生成全數字的驗證碼): 更多PHP教程,請訪問代碼家園session

  1. <img src="checkCode.php?action=NUMBER" width="45" height="20" /> 

 


本文原地址:http://www.daimajiayuan.com/sitejs-16919-1.html函數

相關文章
相關標籤/搜索