相關(guān)關(guān)鍵詞
關(guān)于我們
最新文章
PHP中仿制 ecshop驗證碼實例
仿制ecshop驗證碼的代碼如下所示:
<?php //仿制ecshop驗證碼(四位大寫字母和數(shù)字、背景) //處理碼值(四位大寫字母和數(shù)字組成) //所有的可能的字符集合 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $chars_len = strlen($chars); //集合長度 //隨機選取 $code_len = 4;//驗證碼長度 $code=''; //驗證碼值初始化 for($i=0;$i<$code_len;++$i){ //隨機取得一個字符下標(biāo) $rand_index = mt_rand(0,$chars_len-1); //利用字符串的下標(biāo)操做,獲得選擇的字符 $code .= $chars[$rand_index]; } //echo $code; //存儲于session中(用于校驗) session_start(); $_SESSION['code'] = $code; //驗證碼圖像(已知的背景圖片) //處理背景 $bg_file= './captcha/captcha_bg' . mt_rand(1,5). '.jpg'; //依據(jù)該圖片,創(chuàng)建畫布 $image = imagecreatefromjpeg($bg_file); //簡單的將字符串寫在畫布上的函數(shù)(imageString();) //imageString(畫布,字體,位置X, 位置y,字符串內(nèi)容,顏色); //字體:imagestring函數(shù),使用的內(nèi)置字體。由1-5表示。位置由字符串左上角的坐標(biāo)決定。顏色也是需要預(yù)先分配好的。imagecolorallocate(); //分配字體顏色(隨機分配黑色或者白色) if(mt_rand(0,1)==1){ $str_color = imagecolorallocate($image,0,0,0); //黑色 }else{ $str_color = imagecolorallocate($image,255,0xff,255);//白色 } //內(nèi)置5號字體 $font = 5; //位置 //畫布大小 $image_w = imagesx($image); $image_h = imagesy($image); //獲得字體的寬和高 $font_w = imagefontwidth($font); $font_h = imagefontheight($font); //獲得字符串的寬高 $str_w = $font_w * $code_len; $str_h = $font_h; //計算位置 $str_x = ($image_w-$str_w) / 2; $str_y = ($image_h-$str_h) / 2; //字符串 imagestring($image,$font,$str_x,$str_y,$code,$str_color); //輸出和銷毀畫布 header("content-type:image/jpeg"); imagejpeg($image); imagedestroy($image);