php中怎么實現一個生成驗證碼函數,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

php生成驗證碼的源碼:
<?php
session_start();
//session_register('CheckCode');
//PHP4.2以上版本不需要用session_register()注冊SESSION變量
$type='gif';
$width= 45;
$height= 20;
header("Content-type: image/".$type);
srand((double)microtime()*1000000);
if(isset($_GET['action'])){
$randval=randStr(4,$_GET['action']);
}else{
$randval=randStr(4,'');
}
if($type!='gif'&&function_exists('imagecreatetruecolor')){
$im=@imagecreatetruecolor($width,$height);
}else{
$im=@imagecreate($width,$height);
}
$r=Array(225,211,255,223);
$g=Array(225,236,237,215);
$b=Array(225,236,166,125);
$key=rand(0,3);
$backColor=ImageColorAllocate($im,$r[$key],$g[$key],$b[$key]);//背景色(隨機)
$borderColor=ImageColorAllocate($im,127,157,185);//邊框色
$pointColor=ImageColorAllocate($im,255,170,255);//點顏色
@imagefilledrectangle($im,0,0,$width - 1,$height - 1,$backColor);//背景位置
@imagerectangle($im,0,0,$width-1,$height-1,$borderColor); //邊框位置
$stringColor=ImageColorAllocate($im,255,51,153);
for($i=0;$i<=100;$i++){
$pointX=rand(2,$width-2);
$pointY=rand(2,$height-2);
@imagesetpixel($im,$pointX,$pointY,$pointColor);
}
@imagestring($im,5,5,1,$randval,$stringColor);
$ImageFun='Image'.$type;
$ImageFun($im);
@imagedestroy($im);
$_SESSION['CheckCode']=$randval;
function randStr($len=6,$format='ALL'){
switch($format){
case 'ALL'://生成包含數字和字母的驗證碼
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break;
case 'CHAR'://僅生成包含字母的驗證碼
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; break;
case 'NUMBER'://僅生成包含數字的驗證碼
$chars='0123456789'; break;
default :
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; break;
}
$string='';
while(strlen($string)<$len)
$string.=substr($chars,(mt_rand()%strlen($chars)),1);
return $string;
}該函數的具體使用方法請看如下這個示例(這里是生成全數字的驗證碼):
<img src="checkCode.php?action=NUMBER" width="45" height="20" />
關于php中怎么實現一個生成驗證碼函數問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創新互聯行業資訊頻道了解更多相關知識。
新聞標題:php中怎么實現一個生成驗證碼函數-創新互聯
網址分享:http://www.js-pz168.com/article12/dgddgc.html
成都網站建設公司_創新互聯,為您提供外貿建站、網站維護、品牌網站設計、軟件開發、網站內鏈、域名注冊
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯