驗證碼在表單實現愈來愈多了,可是用js的寫的驗證碼,總以爲不方便,因此學習了下php實現的驗證碼。好吧,實際上是沒有事情幹,可是又不想浪費時間,因此學習了下php實現驗證碼。php
正所謂,技多不壓身。並且,也能夠封裝成一個函數,之後使用的時候也是很方便的,固然如今未封裝。windows
先給你們附上一張效果圖:bash
因爲註冊的時候經常會用到註冊.碼來防止機器惡意註冊,這裏我發表一個產生png圖片驗證碼的基本圖像,很簡陋但思想很清晰:session
一、產生一張png的圖片
二、爲圖片設置背景色
三、設置字體顏色和樣式
四、產生4位數的隨機的驗證碼
五、把產生的每一個字符調整旋轉角度和位置畫到png圖片上
六、加入噪點和干擾線防止註冊機器分析原圖片來惡意註冊
七、輸出圖片
八、釋放圖片所佔內存函數
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\Fonts\文件夾下找到,我把它放到和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);
}
//干擾點
for ($i=0;$i<250;$i++){
imagesetpixel($im,rand(0,$x),rand(0,$y),$fontColor);
}
imagepng($im);
imagedestroy($im);
?>複製代碼
針對PHP驗證碼生成原理和實現的相關知識字體