英文同數字
<?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);
?>