php中文字母數字驗證碼實現代碼_php技巧
來源:互聯網
上載者:User
英文同數字
<?php
Header("Content-type:image/png");
//定義header,聲明圖片檔案,最好是png,無著作權之擾;
//產生新的四位整數驗證碼
session_start();//開啟session;
$authnum_session = '';
$str = 'abcdefghijkmnpqrstuvwxyz1234567890';
//定義用來顯示在圖片上的數字和字母;
$l = strlen($str); //得到字串的長度;
//迴圈隨機抽取四位前面定義的字母和數字;
for($i=1;$i<=4;$i++)
{
$num=rand(0,$l-1);
//每次隨機抽取一位元字;從第一個字到該字串最大長度,
//減1是因為截取字元是從0開始起算;這樣34字元任意都有可能排在其中;
$authnum_session.= $str[$num];
//將通過數字得來的字元連起來一共是四位;
}
session_register("authnum_session");
//用session來做驗證也不錯;註冊session,名稱為authnum_session,
//其它頁面只要包含了該圖片
//即可以通過$_SESSION["authnum_session"]來調用
//產生驗證碼圖片,
srand((double)microtime()*1000000);
$im = imagecreate(50,20);//圖片寬與高;
//主要用到黑白灰三種色;
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
$gray = ImageColorAllocate($im, 200,200,200);
//將四位整數驗證碼繪入圖片
imagefill($im,68,30,$gray);
//如不用幹擾線,注釋就行了;
$li = ImageColorAllocate($im, 220,220,220);
for($i=0;$i<3;$i++)
{//加入3條幹擾線;也可以不要;視情況而定,因為可能影響使用者輸入;
imageline($im,rand(0,30),rand(0,21),rand(20,40),rand(0,21),$li);
}
//字元在圖片的位置;
imagestring($im, 5, 8, 2, $authnum_session, $white);
for($i=0;$i<90;$i++)
{//加入幹擾象素
imagesetpixel($im, rand()%70 , rand()%30 , $gray);
}
ImagePNG($im);
ImageDestroy($im);
?>
中文
<?php
/*
* 檔案:code.php
* 作用:驗證碼產生
*/
session_start();
// 設定 content-type
header("Content-type: image/png");
// 建立圖片
$im = imagecreatetruecolor(120, 30);
$ChineseChar = array("人","出","來","友","學","孝","仁","義","禮","廉","忠","國","中","易","白","者","火 ","土","金","木","雷","風","龍","虎","天","地",
"生","暈","菜","鳥","田","三","百","錢","福 ","愛","情","獸","蟲","魚","九","網","新","度","哎","唉","啊","哦","儀","老","少","日",
"月 ","星");
// 建立顏色
$fontcolor = imagecolorallocate($im, 255, 255, 255);
$bg = imagecolorallocate($im, 0, 0, 0);
// 設定文字
for($i=0;$i<4;$i++) $text .= $ChineseChar[(array_rand($ChineseChar))];
$_SESSION['code'] = $text;
// 設定字型 [url]http://www.font.com.cn/downlist/s_12_3.html[/url] 有_GBK系列的字型下載,一般GD庫都支援的!
$font = 'gbk.ttf';
// 添加文字
imagettftext($im, 18, 0, 11, 21, $fontcolor, $font, iconv("GB2312","UTF-8",$text));
// 輸出圖片
imagepng($im);
imagedestroy($im);
?>