仿制ecshop驗證碼的代碼如下所示:
<?php//仿制ecshop驗證碼(四位大寫字母和數字、背景)//處理碼值(四位大寫字母和數字組成)//所有的可能的字符集合$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';$chars_len = strlen($chars); //集合長度//隨機選取$code_len = 4;//驗證碼長度$code=''; //驗證碼值初始化for($i=0;$i<$code_len;++$i){ //隨機取得一個字符下標 $rand_index = mt_rand(0,$chars_len-1); //利用字符串的下標操做,獲得選擇的字符 $code .= $chars[$rand_index];}//echo $code;//存儲于session中(用于校驗)session_start();$_SESSION['code'] = $code;//驗證碼圖像(已知的背景圖片)//處理背景$bg_file= './captcha/captcha_bg' . mt_rand(1,5). '.jpg';//依據該圖片,創建畫布$image = imagecreatefromjpeg($bg_file);//簡單的將字符串寫在畫布上的函數(imageString();)//imageString(畫布,字體,位置X, 位置y,字符串內容,顏色); //字體:imagestring函數,使用的內置字體。由1-5表示。位置由字符串左上角的坐標決定。顏色也是需要預先分配好的。imagecolorallocate();//分配字體顏色(隨機分配黑色或者白色)if(mt_rand(0,1)==1){ $str_color = imagecolorallocate($image,0,0,0); //黑色 }else{ $str_color = imagecolorallocate($image,255,0xff,255);//白色}//內置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);封裝驗證碼工具類:
//驗證碼工具類(將所有和驗證碼操作相關的全部封裝到該類中) class Captcha{ /*生成驗證碼*/ public function makeImage($code_len=4){ //仿制ecshop驗證碼(四位大寫字母和數字、背景) //處理碼值(四位大寫字母和數字組成) //所有的可能的字符集合 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $chars_len = strlen($chars); //集合長度 //隨機選取 $code=''; //驗證碼值初始化 for($i=0;$i<$code_len;++$i){ //隨機取得一個字符下標 $rand_index = mt_rand(0,$chars_len-1); //利用字符串的下標操做,獲得選擇的字符 $code .= $chars[$rand_index]; } //echo $code; //存儲于session中(用于校驗) @session_start(); $_SESSION['code'] = $code; //驗證碼圖像(已知的背景圖片) //處理背景 $bg_file= TOOL . './captcha/captcha_bg' . mt_rand(1,5). '.jpg'; //依據該圖片,創建畫布 $image = imagecreatefromjpeg($bg_file); //簡單的將字符串寫在畫布上的函數(imageString();) //imageString(畫布,字體,位置X, 位置y,字符串內容,顏色); //字體:imagestring函數,使用的內置字體。由1-5表示。位置由字符串左上角的坐標決定。顏色也是需要預先分配好的。imagecolorallocate(); //分配字體顏色(隨機分配黑色或者白色) if(mt_rand(0,1)==1){ $str_color = imagecolorallocate($image,0,0,0); //黑色 }else{ $str_color = imagecolorallocate($image,255,0xff,255);//白色 } //內置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); }}以上所述是小編給大家介紹的PHP中仿制 ecshop驗證碼實例,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
新聞熱點
疑難解答
圖片精選