由于注冊的時候常常會用到注冊碼來防止機器惡意注冊,這里我發表一個產生png圖片驗證碼的基本圖像,很簡陋但思想很清晰:
1、產生一張png的圖片
2、為圖片設置背景色
3、設置字體顏色和樣式
4、產生4位數的隨機的驗證碼
5、把產生的每個字符調整旋轉角度和位置畫到png圖片上
6、加入噪點和干擾線防止注冊機器分析原圖片來惡意注冊
7、輸出圖片
8、釋放圖片所占內存
authcode.php文件,代碼如下:
- <?php
- session_start ();
- header ( 'content-type: image/png' );
- //創建圖片
- $im = imagecreate($x=130,$y=45 );
- $bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155)); //第一次對 imagecolorallocate() 的調用會給基于調色板的圖像填充背景色
- $fontcolor = imagecolorallocate ( $im, 255, 255, 255 ); //字體顏色
- $fontstyle = 'rock.ttf'; //字體樣式,這個可以從c:windows onts文件夾下找到,我把它放到和authcode.php文件同一個目錄,這里可以替換其他的字體樣式
- //產生隨機字符
- for($i = 0; $i < 4; $i ++) {
- $randasciinumarray = array (rand(48,57),rand(65,90));
- $randasciinum = $randasciinumarray [rand ( 0, 1 )];
- $randstr = chr ( $randasciinum );
- imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontcolor,$fontstyle,$randstr);
- $authcode .= $randstr;
- }
- $_session['authcode'] = $randfourstr;//用戶和用戶輸入的驗證碼做比較
- //干擾線
- for ($i=0;$i<8;$i++){
- $linecolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
- imageline ($im,rand(0,$x),0,rand(0,$x),$y,$linecolor);
- }//開源代碼Vevb.com
- //干擾點
- for ($i=0;$i<250;$i++){
- imagesetpixel($im,rand(0,$x),rand(0,$y),$fontcolor);
- }
- imagepng($im);
- imagedestroy($im);
- ?>
新聞熱點
疑難解答