php生成隨機驗證碼圖片的示例代碼
更新時間:2023年09月19日 09:58:43 作者:祈愿lucky
這篇文章主要介紹了php生成隨機驗證碼圖片的示例代碼,結(jié)合實例形式分析了php生成隨機驗證碼圖片的實現(xiàn)方法與相關(guān)操作注意事項,文中有詳細的代碼示例,需要的朋友可以參考下
1,CaptchaPicture.php用于生成畫布,然后在畫布上生成四位隨機驗證碼
<?php session_start(); header("Content-type:image/png"); //創(chuàng)建圖像的格式 $image_width=76; //設(shè)置圖像的寬度 $image_height=40; //設(shè)置圖像的高度 $length=4; //字符串長度為4 //除去0,2,o,l容易混淆的字符 $str="23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKMNOPQRSRUVWXYZ"; $code=''; for($i=0;$i<$length;$i++){ $code.=$str[mt_rand(0,strlen($str))-1]; //從字符串中隨機選擇 } $_SESSION['verify']=$code; //從獲取到的隨機書驗證碼寫入到Session變量中 $image=imagecreate($image_width,$image_height); //創(chuàng)建一個畫布 imagecolorallocate($image,25,255,255); //設(shè)置畫布的顏色 For($i=0;$i<strlen($_SESSION['verify']);$i++){ //循環(huán)讀取Session變量中的驗證碼 $font = mt_rand(3,5); //設(shè)置隨機的字體 $x=mt_rand(1,8)+$image_width*$i/4; //設(shè)置隨機字符所在位置的x坐標 $y=mt_rand(8,$image_height/4); //設(shè)置隨機字符所在位置的y坐標 //設(shè)置字符顏色 $color = imagecolorallocate($image,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)); imagestring($image,$font,$x,$y,$_SESSION['verify'][$i],$color); //水平輸出字符 } //繪制干擾元素點 $pixel=30; $black = imagecolorallocate($image,0,0,0); for($i=0;$i<$pixel;$i++){ imagesetpixel($image,mt_rand(0,$image_width-1),mt_rand(0,$image_height-1),$black); } imagepng($image); //生成png格式的圖像 imagedestroy($image); //釋放圖片資源 ?>
2,SubmitVerify.php用于做一個簡單的測試,驗證驗證碼功能是否正常
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="CheckLogin.php" method="post"> <div class="verify"> <input type="text" id="verify" name="verify" class="input" placeholder="驗證碼"> <a> <img src="CaptchPicture.php" onclick="this.src=this.src+'?'+Math.random()"> //單擊驗證碼生成新的驗證碼 </a> </div> <button type="submit">提交</button> </form> </body> </html>
3,CheckLogin.php用于驗證提交后是否能接受到傳遞的信息,以及判斷輸入的驗證碼和生成的驗證碼是否一致
<?php session_start(); $checks = $_POST["verify"]; //獲取表單提交的驗證碼(用戶輸入的驗證碼) if ($checks=="") { echo "<script>alert('驗證碼不能為空'); window.location.href='SubmitVerify.php';</script>"; } if ($checks==$_SESSION["verify"]){ //這個獲取的是系統(tǒng)隨機生成的驗證碼 echo "<script>alert('登錄成功');</script>"; }else{ echo "<script>alert('你輸入的驗證碼不正確!') window.location.href='SubmitVerify.php' </script>"; }
到此這篇關(guān)于php生成隨機驗證碼圖片的示例代碼的文章就介紹到這了,更多相關(guān)php生成隨機驗證碼圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!