首頁  >  文章  >  後端開發  >  PHP如何實作登入驗證碼校驗功能

PHP如何實作登入驗證碼校驗功能

墨辰丷
墨辰丷原創
2018-05-17 11:35:221902瀏覽

這篇文章主要為大家詳細介紹了PHP實現驗證碼校驗功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下

驗證碼的校驗是利用PHP中的SESSION功能來實作。
在最頂端宣告函數 session_start(); 告訴伺服器我們要用這個函數的函數。


session_start();


接下來我們用到的就是驗證碼實作的程式碼。這裡用英文數字的代碼為例。


$image = imagecreatetruecolor(100, 30); //创建一个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(&#39;a&#39;,&#39;z&#39;),range(&#39;A&#39;,&#39;Z&#39;),range(0,9))); 
  $char = str_shuffle($char); 
  $char = substr($char,0,1); 
  imagestring($image,$size,$x,$y,$char,$sizi_color); 
  $session .= $char ; //把验证码的每一个值赋值给变量 
} 
  $_SESSION[&#39;session&#39;] = $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(&#39;content-type:image/png&#39;);//设置文件输出格式 
imagepng( $image ); //以png格式输出$image图像 
imagedestroy( $image ); //销毁图像


用POST 方式來接收驗證碼。 strtolower 函數是讓伺服器不區分大小寫。這樣可以有效減少使用者的輸錯率。


if(isset($_POST[&#39;session&#39;])){ 
  session_start(); 
  if(strtolower($_POST[&#39;session&#39;])==strtolower($_SESSION[&#39;session&#39;])){ 
    echo&#39;<font color="#0000CC">输入正确</form>&#39;; 
  }else{ 
    echo &#39;<font color="#CC0000"><b>输入错误</b></font>&#39;; 
  } 
  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(&#39;img&#39;).src=&#39;http://localhost//xxx.php&#39;">看不清?换一个</a> 
  <p>请输入图片中的验证码:<input type="text" name="session" value=""/></p> 
  <p><input type="submit" value="提交" style="padding:6px 10px;"></p> 
  </form> 
</body> 
</html>

相關推薦:

php如何利用雲端片網實作簡訊驗證碼功能

php 驗證碼封裝類別

laravel操作簡訊傳送驗證碼功能實作步驟詳解

#

以上是PHP如何實作登入驗證碼校驗功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn