本款php生成驗證碼代碼原理生成隨機數-->創建圖片-->隨機數寫進圖片-->保存在session中,看一下流程驗證碼圖片生成 通知瀏覽器將要輸出PNG圖片,準備好隨機數發生器種子 srand((double)microtime()*1000000); 將四位整數驗證碼繪入圖片.
php加入干擾的生成驗證碼代碼如下:
- /*=====================
- 產生隨機字符串函數
- =====================*/
- function random($length) {
- $hash = '';
- $chars = 'abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz';
- $max = strlen($chars) - 1;
- mt_srand((double)microtime() * 1000000);
- for($i = 0; $i < $length; $i++) {
- $hash .= $chars[mt_rand(0, $max)];
- }
- return $hash;
- }
- //驗證碼圖片生成
- session_start();
- //通知瀏覽器將要輸出png圖片
- header("content-type: image/png");
- //準備好隨機數發生器種子
- //srand((double)microtime()*1000000);
- //準備圖片的相關參數
- $im = imagecreate(62,22);
- $black = imagecolorallocate($im, 0,0,0); //rgb黑色標識符
- $white = imagecolorallocate($im, 255,255,255); //rgb白色標識符
- $gray = imagecolorallocate($im, 179,183,185); //rgb灰色標識符
- //開始作圖
- imagefill($im,0,0,$gray);
- //while(($randval=rand()%100000)<10000);{
- //$_session["check_code"] = $randval;
- //將四位整數驗證碼繪入圖片
- $randval=random(4);
- $_session["check_code"]=$randval;
- imagestring($im, 5, 10, 3, $randval, $white);
- //}
- //加入干擾象素
- for($i=0;$i<150;$i++){
- $randcolor = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
- imagesetpixel($im, rand()%70 , rand()%30 , $white);
- } //開源代碼Vevb.com
- //輸出驗證圖片
- imagepng($im);
- //銷毀圖像標識符
- imagedestroy($im);
新聞熱點
疑難解答