登錄頁面代碼login:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登陸</title> </head> <body> <form action="./test.php" method="post"> <img src="image_captcha.php" onclick="this.src='image_captcha.php?'+new Date().getTime();" width="140" height="35"><br/> <input type="text" name="captcha" placeholder="請輸入圖片中的驗證碼"><br/> <input type="submit" value="驗證"> </form> </body> </html>
生成驗證代碼:
<?php /** * 字母+數字的驗證碼生成 */ // 開啟session session_start(); //1.創建黑色畫布 $image = imagecreatetruecolor(100, 30); //2.為畫布定義(背景)顏色 $bgcolor = imagecolorallocate($image, 255, 255, 255); //3.填充顏色 imagefill($image, 0, 0, $bgcolor); // 4.設置驗證碼內容 //4.1 定義驗證碼的內容 $content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; //4.1 創建一個變量存儲產生的驗證碼數據,便於用戶提交核對 $captcha = ""; for ($i = 0; $i < 4; $i++) { // 字體大小 $fontsize = 10; // 字體顏色 $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); // 設置字體內容 $fontcontent = substr($content, mt_rand(0, strlen($content)), 1); $captcha .= $fontcontent; // 顯示的坐標 $x = ($i * 100 / 4) + mt_rand(5, 10); $y = mt_rand(5, 10); // 填充內容到畫布中 imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor); } $_SESSION["image_captcha"] = $captcha; //4.3 設置背景干擾元素 for ($$i = 0; $i < 200; $i++) { $pointcolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200)); imagesetpixel($image, mt_rand(1, 99), mt_rand(1, 29), $pointcolor); } //4.4 設置干擾線 for ($i = 0; $i < 3; $i++) { $linecolor = imagecolorallocate($image, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200)); imageline($image, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $linecolor); } //5.向瀏覽器輸出圖片頭信息 header('content-type:image/png'); //6.輸出圖片到瀏覽器 imagepng($image); //7.銷毀圖片 imagedestroy($image);
驗證輸入代碼:
<?php /** * 接受用戶登陸時提交的驗證碼 */ session_start(); //1. 獲取到用戶提交的驗證碼 $captcha = $_POST["captcha"]; //2. 將session中的驗證碼和用戶提交的驗證碼進行核對,當成功時提示驗證碼正確,不成功則跳回重新提交 if(strtolower($_SESSION["image_captcha"]) == strtolower($captcha)){ echo "<h5>yes!驗證碼正確!</h5>"; }else{ echo "NO! 驗證碼提交不正確!"; header("refresh:3;url=./login.php");//輸入錯誤跳轉登錄頁面 }