《PHP實戰:使用php實現網站驗證碼功能【推薦】》要點:
本文介紹了PHP實戰:使用php實現網站驗證碼功能【推薦】,希望對您有用。如果有疑問,可以聯系我們。
PHP實戰驗證碼是網站常用的一項安全措施,也是新人站長較難掌握的一項技能,這里我向大家介紹一簡單有效的驗證碼實現方法.
PHP實戰開始之前
PHP實戰在正式開始之前我們需要打開php的gd2圖形庫支持(在php.ini,中搜索“php_gd2.dll”,找到“;extension=php_gd2.dll”并去掉句首的分號) .
PHP實戰可以參考:如何打開php的gd2庫
PHP實戰核心:img.php
PHP實戰這個頁面生成一張驗證碼并將正確數值寫入 Session
PHP實戰隨機一個4位驗證碼
PHP實戰$check=rand(1000,9999);?
PHP實戰將生成的驗證碼寫入session
PHP實戰
Session_start();
$_SESSION["check"] = $check;
PHP實戰創建一張圖片
PHP實戰$im = imagecreate(80,30);
PHP實戰由于這種圖片的背景默認是黑色的所以我們要用白色填充.
PHP實戰imagefill($im,0,0,ImageColorAllocate($im, 255,255,255));?
PHP實戰使用imageline隨機繪制兩條實線
PHP實戰
$y1=rand(0,30);
$y2=rand(0,30);
$y3=rand(0,30);
$y4=rand(0,30);
imageline($im,0,$y1,70, $y3,000);
imageline($im,0,$y2,70, $y4,000);
PHP實戰在隨機位置繪制文字
PHP實戰
$strx=rand(3,15);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,0,1),ImageColorAllocate($img,34,87,100));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,1,1),ImageColorAllocate($img,781,117,78));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,2,1),ImageColorAllocate($img,160,40,40));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,3,1),ImageColorAllocate($img,25,55,10));
PHP實戰輸出圖像
PHP實戰
Header("Content-type: image/PNG");
ImagePNG($img);
PHP實戰結束,下面是完整代碼
PHP實戰
<?php $check=rand(1000,9999);
Session_start();
$_SESSION["check"] = $check;
$img = imagecreate(80,30);
imagefill($img,0,0,ImageColorAllocate($img,255,255,255));
$y1=rand(0,30);
$y2=rand(0,30);
$y3=rand(0,30);
$y4=rand(0,30);
imageline($img,0,$y1,70, $y3,ImageColorAllocate($img,55,255,25));
imageline($img,0,$y2,70, $y4,ImageColorAllocate($img,55,55,255));
$strx=rand(3,15);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,0,1),ImageColorAllocate($img,34,87,100));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,1,1),ImageColorAllocate($img,781,117,78));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,2,1),ImageColorAllocate($img,160,40,40));
$strx+=rand(15,20);
$stry=rand(2,15);
imagestring($img,5,$strx,$stry,substr($check,3,1),ImageColorAllocate($img,25,55,10));
Header("Content-type: image/PNG");
ImagePNG($img);
PHP實戰用戶界面:index.php
PHP實戰想必大家都知道怎么做,我就直接給出代碼了
PHP實戰
<!DOCTYPE html>
<html>
<body>
<form action="action.php" method="post">
<input type="text" name="cikle" placeholder="驗證碼">
<br>
<img id="cikle" style="-webkit-user-select: none" src="img.php"><input type="submit" value="Submit">
</form>
</body>
</html>
PHP實戰以上的代碼將用戶輸入的數值傳遞到“action.php”中
PHP實戰檢查:action.php
PHP實戰這一步要將用戶輸入數值與session中的數值進行比對
PHP實戰相等,輸出“正確”
PHP實戰不相等,輸出“不正確”
PHP實戰
<?php
Session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if($_SESSION["check"]!=intval($_POST["cikle"])){
echo "不正確";
}else{
echo "正確";
}
}
PHP實戰以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持維易PHP!
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/1828.html