1、首先來一個html頁面 index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>注冊</title> </head> <body> <form action="./register.php" method="post"> <img src="Verify.php" onclick="this.src='Verify.php?'+new Date().getTime();" width="100" height="100"><br/> <input type="text" name="verify" placeholder="請輸入圖片中的驗證碼"><br/> <input type="submit" value="驗證"> </form> </body> </html>
2、驗證碼 register.php
<?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["verifyimg"] = $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); ?>
3、提交驗證驗證碼頁面register.php
<?php /** * 接受用戶登陸時提交的驗證碼 */ session_start(); //1. 獲取到用戶提交的驗證碼 $verify = $_POST["verify"]; //2. 將session中的驗證碼和用戶提交的驗證碼進行核對,當成功時提示驗證碼正確,並銷毀之前的session值,不成功則重新提交 if(strtolower($_SESSION["verifyimg"]) == strtolower($verify)){ echo "ok"; $_SESSION["verify"] = ""; }else{ echo "error"; } ?>
4、如果不需要干擾線或者背景干擾元素,直接把里面的內容注釋就好了,效果就這樣的
最后來一個小問題,我再win系統上可以顯示,傳到服務器,圖片不顯示,可以超看一下是否開啟了GD庫,怎么操作,先自行百度,我有空再寫。