利用PHP函式生成驗證碼圖片,在透過 session & AJAX 實現及時驗證
index.php (測試頁面)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Language" content="zh-tw" /> <title>PHP+AJAX實作簡易圖形驗證碼</title> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <form action="" id="reg_form" method="POST"> <p>驗證碼:( 點擊圖片可以更換驗證碼)<br></p> <img id="imgcode" src="imgcode.php" onclick="refresh_code()" /><br> <p><input type="text" name="vcode" value="" placeholder="輸入上方圖形驗證碼" class="form-control form-control-user reg_vcode" id="reg_vcode"><span class="vcode_hint"></span> </p> <button type="button" class="red_button form-btn">送出</button> </form> <script type="text/javascript"> //javascript function refresh_code(){ document.getElementById("imgcode").src="imgcode.php"; } var vcode_Boolean = false; //偵測輸入 $('.reg_vcode').blur(function(){ if ((/^[a-zA-Z0-9_-]{4,4}$/).test($(".reg_vcode").val())){//判定輸入值 var acode=document.getElementById("reg_vcode").value; $.ajax({ type:"POST", url:"ajax.php", data:"data="+acode+"&action=chkvcode", cache:false, success:function(data){ //回傳資料 if(data == 'OK'){ $('.vcode_hint').html(" ✔ ").css("color","green"); $('.reg_vcode').css("border","1px solid green"); vcode_Boolean = true; }else{ $('.vcode_hint').html(" × 驗證錯誤").css("color","red"); $('.reg_vcode').css("border","1px solid red"); vcode_Boolean = false; } } }); }else { $('.vcode_hint').html(" × 驗證錯誤").css("color","red"); $('.reg_vcode').css("border","1px solid red"); vcode_Boolean = false; } }); // click $('.red_button').click(function(){ if(vcode_Boolean == true){ document.getElementById("reg_form").submit(); }else { alert("請確認資料輸入正確"); } }); </script> </body> </html>
程式說明
AJAX需要jquery的支持,需要先引入jquery的js檔
利用span來接收回傳的資料
把送出按鈕的submit type改成button,讓他執行js不直接送出資料
function refresh_code 用於刷新驗證圖片
imgcode.php (生成圖片的php檔)
<?php if(!isset($_SESSION)){ session_start(); } //檢查SESSION是否啟動 $_SESSION['check_word'] = ''; //設置存放檢查碼的SESSION //設置定義為圖片 ob_clean(); header("Content-type: image/PNG"); /* imgcode($nums,$width,$high) 設置產生驗證碼圖示的參數 $nums 生成驗證碼個數 $width 圖片寬 $high 圖片高 */ imgcode(4,120,30); //imgcode的function function imgcode($nums,$width,$high) { $str = "0123456789"; $code = ''; for ($i = 0; $i < $nums; $i++) { $code .= $str[mt_rand(0, strlen($str)-1)]; } $_SESSION['check_word'] = $code; //建立圖示,設置寬度及高度與顏色等等條件 $image = imagecreate($width, $high); $black = imagecolorallocate($image, mt_rand(0, 200), mt_rand(0, 200), mt_rand(0, 200)); $border_color = imagecolorallocate($image, 21, 106, 235); $background_color = imagecolorallocate($image, 235, 236, 237); //建立圖示背景 imagefilledrectangle($image, 0, 0, $width, $high, $background_color); //建立圖示邊框 imagerectangle($image, 0, 0, $width-1, $high-1, $border_color); //在圖示布上隨機產生大量躁點 for ($i = 0; $i < 80; $i++) { imagesetpixel($image, rand(0, $width), rand(0, $high), $black); } $strx = rand(3, 8); for ($i = 0; $i < $nums; $i++) { $strpos = rand(1, 6); imagestring($image, 5, $strx, $strpos, substr($code, $i, 1), $black); $strx += rand(10, 30); } imagepng($image); imagedestroy($image); } ?>
程式說明
imagecreate():建立一幅空白圖像
使用方法:imagecreate ( int $width , int $height )
$width:圖像的寬度
$height:圖像的高度
(參考資料:http://php.net/manual/en/function.imagecreate.php)
imagecolorallocate():分配圖像的顏色
使用方法:imagecolorallocate ( $image , $red , $green , $blue )
$image:圖像資源,通過圖像產生功能
顏色由RGB成份所組成
$red:紅色的數值
$green:綠色的數值
$blue:藍色的數值
(參考資料:http://php.net/manual/en/function.imagecolorallocate.php)
imagefilledrectangle():產生一個矩形圖像並填滿指定顏色
使用方法:imagefilledrectangle ( $image , $x1 , $y1 , $x2 , $y2 , $color )
$image:圖像資源,通過圖像產生功能
$x1:左上x坐標點
$y1:左上y坐標點
$x2:右下x坐標點
$y2:右下y坐標點
$color:填滿顏色
(參考資料:http://php.net/manual/en/function.imagefilledrectangle.php)
imagerectangle():產生一個指定顏色的矩形
imagerectangle ( $image , $x1 , $y1 , $x2 , $y2 , $color )
$image:圖像資源,通過圖像產生功能
$x1:左上x坐標點
$y1:左上y坐標點
(0,0是圖像的左上角)
$x2:右下x坐標點
$y2:右下y坐標點
$color:填滿指定顏色
(參考資料:http://php.net/manual/en/function.imagerectangle.php)
imagesetpixel():設定單一像素
使用方法:imagesetpixel ( $image , $x , $y , $color )\
$image:圖像資源,通過圖像產生功能
$x:x坐標點
$y:y坐標點
$color:填滿指定顏色
(參考資料:http://php.net/manual/en/function.imagesetpixel.php)
imagestring():
使用方法:imagestring ( $image, $font, $x, $y, $string, $color )
$image:圖像資源,通過圖像產生功能
$font:指定字型,有1,2,3,4 ,5,使用內建字型
$x:x坐標點
$y:y坐標點
$string:將要寫入的字串
$color:填滿指定顏色
(參考資料:http://php.net/manual/en/function.imagestring.php)
imagepng():以PNG格式將圖像輸出
使用方法:imagepng ( $image )
$image:圖像資源,通過圖像產生功能
(參考資料:http://php.net/manual/en/function.imagepng.php)
imagedestroy():釋放與圖像相關的任何資源
使用方法:imagedestroy ( $image )
$image:圖像資源,通過圖像產生功能
(參考資料:http://php.net/manual/en/function.imagedestroy.php)
ajax.php (驗證程式)
<?php if(!isset($_SESSION)){session_start();} //開啟 SESSION if (isset($_POST['action'])) { if (isset($_POST['data'])){$data=$_POST['data'];}else{$data='';} switch ($_POST['action']){ case "chkvcode": /*ajax chkvcode*/ if(!empty($_SESSION['check_word'])){ //判斷此兩個變數是否為空 if($_SESSION['check_word'] == $data){ echo "OK"; }else{ echo "驗證碼錯誤"; } }else{ echo "驗證碼錯誤"; } break; } } ?>
執行結果

留言板