PHP實作登入驗證碼功能

墨辰丷
發布: 2023-03-26 07:34:01
原創
7304 人瀏覽過

本篇文章主要介紹PHP如何寫登入驗證碼的功能,有興趣的朋友參考下,希望對大家有幫助。

在最頂端宣告函數 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編寫登入驗證碼功能附呼叫方法

java登入驗證碼實作程式碼

MVC使用極驗驗證製作登入驗證碼

#

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

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!