>  기사  >  백엔드 개발  >  PHP+Ajax는 사용자 로그인을 확인하기 위해 확인 코드를 구현합니다.

PHP+Ajax는 사용자 로그인을 확인하기 위해 확인 코드를 구현합니다.

墨辰丷
墨辰丷원래의
2018-06-01 17:00:173556검색

이 글은 주로 사용자 로그인을 확인하기 위한 PHP+AJAX 인증 코드 관련 정보를 자세하게 소개하고 있으니 관심 있는 분들이 참고하시면 좋을 것 같습니다.

사용자 로그인을 확인하기 위해 AJAX를 사용하면 점프 페이지를 새로 고칠 필요가 없다는 장점도 있고, 인증 코드를 사용하는 것이 더 안전하기 때문에 잠시 후에 적어 두었습니다. 총 3개의 파일이 사용됩니다:

yz.php: 인증 코드를 생성하는 PHP 파일은 로그인 시 비교 및 ​​호출을 위해 SESSION에 있습니다.
index.php: 사용자 로그인용 HTML 파일
loginCheck.php: 사용자 로그인 확인용 파일

은 아래에서 하나씩 분석됩니다.
yz.php 파일

<?php
 session_start();

 //生成验证码图
 Header("Content-type: image/PNG");
 //长与宽
 $im = imagecreate(44,18);
 // 设置背景色:
 $back = ImageColorAllocate($im, 245,245,245);
 // 填充背景色:
 imagefill($im,0,0,$back);

 srand((double)microtime()*1000000);
 $vcodes;
 //生成4位数字
 for($i=0;$i<4;$i++){
  $font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255));
  $authnum=rand(1,9);
  $vcodes.=$authnum;
  imagestring($im, 5, 2+$i*10, 1, $authnum, $font);
 }

 //加入干扰象素
 for($i=0;$i<100;$i++){
  $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
  imagesetpixel($im, rand()%70 , rand()%30 , $randcolor);
 }
  
 ImagePNG($im);
 ImageDestroy($im);

 // 将四位的验证码保存在 SESSION 里,登录时调用对比
 $_SESSION["VCODE"]=$vcodes;
?>

색인. php: 이 파일에서는 $_SESSION["VCODE"]를 사용하지 마세요. 그렇지 않으면 한 단계 나중에 수행되고 새로 고침 후에 이전 인증 코드가 표시됩니다. loginCheck.php


에서 확인하세요.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>管理后台| 请登录</title>
<link rel="stylesheet" type="text/css" href="\css\a.css">
<style type="text/css">
<!--
  #main{
   font-family:宋体;
   font-size:10pt;
   text-align:center;
   margin-top:510px;
  }
  
  body{
   background-attachment:fixed;
   background-position:center;
   background-image:url(./images/w2.jpg);
   background-repeat: no-repeat;
  }
  
  #authCode{background-Color:#F8F9FF;}
  
  table{text-align:center;}

//-->
</style>
<script type="text/javascript" src="./js/trim.js"></script>
<script type="text/javascript">
<!--

 function clearX(){
  document.getElementById(&#39;authCode&#39;).value="";
 }

 // 点击图片重新获得新的验证码:
 function getVCode() { 
  var vcode=document.getElementById(&#39;vcode&#39;); 
  vcode.src =&#39;yz.php?nocache=&#39;+new Date().getTime(); 
 }


 //定义XMLHttpRequest对象
 var xmlHttp;     

 // 创建 XMLHttpRequest:
 function createXmlHttpRequest(){
 var xmlHttp=null;
 try{
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
 }catch(e){
  // Internet Explorer
  try{
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
 return xmlHttp;
 }

 // AJAX 检查登录: 有密码,要用POST 提交
 function login(){
  var authCode=trim(document.getElementById(&#39;authCode&#39;).value);
  var username=trim(document.getElementById(&#39;username&#39;).value);
  var password=trim(document.getElementById(&#39;password&#39;).value);
  if(username=="" || password=="" || authCode==""){
   alert("请输入用户名和密码和验证码!");
   return false;
  }else{
   if(!xmlHttp) xmlHttp=createXmlHttpRequest();
    var send_string="username="+username+"&password="+password+"&authCode="+authCode+"&fresh="+Math.random();
    xmlHttp.open("POST","loginCheck.php",true); 
    xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
    xmlHttp.send(send_string); 
    xmlHttp.onreadystatechange=function(){
     if(xmlHttp.readystate==4 && xmlHttp.status==200){
      var answer=xmlHttp.responseText;
      if(answer=="ok")                     //跳转到管理中心页面
       window.location.href="adminCenter.php";
      else{
       alert("用户名密码或验证码不正确! 请重新输入!");
       document.getElementById(&#39;username&#39;).focus();
      }
    }
   }
  }
 }

//-->
</script>
</head>
<body onload="document.getElementById(&#39;username&#39;).focus();">
 <p id="main">
   <table>
     <tr>
     <td>用户名:<input type="text" id="username" /></td>
     <td>密   码:<input type="password" id="password" /></td>
     <td>验证码:<input type="text" id="authCode" size="6" maxlength="4" value="验证码" onfocus="clearX()"/></td>
     <td><img id="vcode" src="yz.php" alt="看不清?点击换一张" onclick="getVCode()" /></td>
     <td><input id="loginButton" type="submit" value="登 录" onclick="login()"/></td>
     </tr>
    </table>
 </p>
</body>
</html>

loginCheck.php

사용자 로그인 확인 파일

<?php 
 session_start();
 include("../conn/connDB.php");
 
 // 取得POST过来的参数:
 $username=$_POST["username"];
 $password=md5($_POST["password"]);
 $authCode=$_POST["authCode"];       
 
 $feedback="no";

//对比是否==SESSION中的验证码,不能放在客户端做,否则取不正确的值
 if($authCode==$_SESSION["VCODE"]){

   $SQL="select * from users where username=&#39;$username&#39; and password=&#39;$password&#39;";
   $result=mysql_query($SQL);
   $rows=mysql_num_rows($result);
  if($rows==1)                       // 验证成功
   $feedback="ok";
   $_SESSION["admin"]=true;           //为了后台安全,存入SESSION,表明 ADMIN 已登录,供后面调用
  }
  
 echo $feedback;
 
?>

요약: 위 내용은 이 글의 전체 내용입니다. 모두의 학습에 도움이 되기를 바랍니다.

관련 권장 사항:

PHP 객체 지향 프로그래밍 OOP 상속 사용에 대한 자세한 설명


PHP 객체 지향 프로그래밍 클래스의 정의 및 사용법에 대한 자세한 설명


PHP MYSQL 간단한 대화형 사이트 개발 상세 설명


위 내용은 PHP+Ajax는 사용자 로그인을 확인하기 위해 확인 코드를 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.