PHP實現驗證碼校驗功能
驗證碼的校驗是利用PHP中的 SESSION功能來實現。
在最頂端聲明函數 session_start(); 告訴服務器我們要用這個函數的功能。
session_start();
接下來我們用到的就是驗證碼實現的代碼。這里用英文數字的代碼為例。
$image = imagecreatetruecolor(100, 30); //創(chuàng)建一個100×30的畫布 $white = imagecolorallocate($image,255,255,255);//白色 imagefill($image,0,0,$white);//覆蓋黑色畫布
然后在驗證碼實現之前聲明一個空變量,用來存放驗證碼。
$session = ""; //空變量 ,存放驗證碼 for($i=0;$i<4;$i++){ $size = 6; $x = $i*25+mt_rand(5,10); $y = mt_rand(5,10); $sizi_color = imagecolorallocate($image,mt_rand(80,220),mt_rand(80,220),mt_rand(80,220)); $char = join("",array_merge(range('a','z'),range('A','Z'),range(0,9))); $char = str_shuffle($char); $char = substr($char,0,1); imagestring($image,$size,$x,$y,$char,$sizi_color); $session .= $char ; //把驗證碼的每一個值賦值給變量 } $_SESSION['session'] = $session; //這個變量的值與用戶輸入的值相等
for($k=0;$k<200;$k++){ $rand_color = imagecolorallocate($image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200)); imagesetpixel($image,mt_rand(1,99),mt_rand(1,29),$rand_color); } for($n=0;$n<5;$n++){ $line_color = imagecolorallocate($image,mt_rand(80,220),mt_rand(80,220),mt_rand(80,220)); imageline($image,mt_rand(1,99),mt_rand(1,29),mt_rand(1,99),mt_rand(1,29),$line_color); } header('content-type:image/png');//設置文件輸出格式 imagepng( $image ); //以png格式輸出$image圖像 imagedestroy( $image ); //銷毀圖像
用 POST 方式來接收驗證碼。 strtolower 函數是讓服務器不區(qū)分大小寫。這樣可以有效減少用戶的輸錯率。
if(isset($_POST['session'])){ session_start(); if(strtolower($_POST['session'])==strtolower($_SESSION['session'])){ echo'<font color="#0000CC">輸入正確</form>'; }else{ echo '<font color="#CC0000"><b>輸入錯誤</b></font>'; } exit(); }
下面是HTML的頁面代碼。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>確認驗證碼</title> </head> <body> <form method="post" action="./tushu.php"> <p>驗證碼圖片:<img id="img" border="1" src="http://localhost//xxx.php" width="100" height="30"></p> <a href="javascript:void(0)" rel="external nofollow" onclick="document.getElementById('img').src='http://localhost//xxx.php'">看不清?換一個</a> <p>請輸入圖片中的驗證碼:<input type="text" name="session" value=""/></p> <p><input type="submit" value="提交" style="padding:6px 10px;"></p> </form> </body> </html>
這里特別說明一下 HTML代碼中加入了一個事件 onclick .當用戶無法識別當前驗證碼的時候可以不用刷新瀏覽器,直接點擊“看不清?換一個”即可更換驗證碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PHP中通過exec調用python腳本報ModuleNotFoundError錯誤問題及解決方法
這篇文章主要介紹了解決php中通過exec調用python腳本報ModuleNotFoundError錯誤,本文是在 Ubuntu 20.04 上以 ubuntu 用戶身份進行的測試,需要的朋友可以參考下2023-07-07Laravel執(zhí)行migrate命令提示:No such file or directory的解決方法
這篇文章主要介紹了Laravel執(zhí)行migrate命令提示:No such file or directory的解決方法,分析了執(zhí)行migrate命令出現錯誤的原因與相關的解決方法,需要的朋友可以參考下2016-03-03Laravel訪問出錯提示:`Warning: require(/vendor/autoload.php): faile
這篇文章主要介紹了Laravel訪問出錯提示:`Warning: require(/vendor/autoload.php): failed to open stream: No such file or di解決方法,涉及Laravel框架相關配置與安裝操作技巧,需要的朋友可以參考下2019-04-04關于PHP虛擬主機概念及如何選擇穩(wěn)定的PHP虛擬主機
PHP是一種HTML內嵌式的語言,是一種在端執(zhí)行的嵌入HTML文檔的腳本語言,語言的風格有類似于C語言,現在被很多的網站編程人員廣泛的運用。這篇文章給大家分享關于PHP虛擬主機概念及如何選擇穩(wěn)定的PHP虛擬主機,感興趣的朋友一起看看吧2018-11-11