PHP-製作驗證碼
阿新 • • 發佈:2021-10-29
<?php //11>設定session,必須處於指令碼最頂部 session_start(); $image = imagecreatetruecolor(100, 30); //1>設定驗證碼圖片大小的函式 //5>設定驗證碼顏色 imagecolorallocate(int im, int red, int green, int blue); $bgcolor = imagecolorallocate($image, 255, 255, 255); //#ffffff //6>區域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的區域著色,col 表示欲塗上的顏色 imagefill($image, 0, 0, $bgcolor); //10>設定變數 $captcha_code = ""; //7>生成隨機的字母和數字 for ($i = 0; $i < 4; $i++) { //設定字型大小 $fontsize = 8; //設定字型顏色,隨機顏色 $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120)); //0-120深顏色 //設定需要隨機取的值,去掉容易出錯的值如0和o $data = 'abcdefghigkmnpqrstuvwxy3456789'; //取出值,字串擷取方法 strlen獲取字串長度 $fontcontent = substr($data, rand(0, strlen($data)), 1); //10>.=連續定義變數 $captcha_code .= $fontcontent; //設定座標 $x = ($i * 100 / 4) + rand(5, 10); $y = rand(5, 10); imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); } //10>存到session $_SESSION['authcode'] = $captcha_code; //8>增加干擾元素,設定雪花點 for ($i = 0; $i < 200; $i++) { //設定點的顏色,50-200顏色比數字淺,不干擾閱讀 $pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200)); //imagesetpixel — 畫一個單一畫素 imagesetpixel($image, rand(1, 99), rand(1, 29), $pointcolor); } //9>增加干擾元素,設定橫線 for ($i = 0; $i < 4; $i++) { //設定線的顏色 $linecolor = imagecolorallocate($image, rand(80, 220), rand(80, 220), rand(80, 220)); //設定線,兩點一線 imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor); } //2>設定頭部,image/png header('Content-Type: image/png'); //3>imagepng() 建立png圖形函式 imagepng($image); //4>imagedestroy() 結束圖形函式 銷燬$image imagedestroy($image);