Home Backend Development PHP Tutorial How to write PHP login function

How to write PHP login function

Jun 05, 2018 pm 05:50 PM
ajax mysql php Login

This article mainly introduces how to write the PHP login function. Interested friends can refer to it. I hope it will be helpful to everyone.

The specific code is as follows:

1 login.php
In the login interface, the javascript script uses ajax to asynchronously request dologin.php, which is responsible for user information. Verification (including verification code, PHP generates verification code and can search by yourself). The code of the login interface is as follows:

<?php session_start();?>
<!DOCTYPE html>
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 <title>login</title>
 <link rel="stylesheet" type="text/css" href="CSS/login.css" />
 <script src="JS/ajaxhelper.js" type="text/javascript"></script>
 <script src="JS/jquery-1.3.2.min.js" type="text/javascript"></script>
 <script type="text/javascript">
  function chkForm() {
   if (m$(&#39;username&#39;).value == "") {

    alert(&#39;用户名不能为空.&#39;);
    m$(&#39;username&#39;).focus();
    return false;

   }
   if (m$(&#39;password&#39;).value == "") {

    alert(&#39;密码不能为空.&#39;);
    m$(&#39;password&#39;).focus();
    return false;

   }
   if (m$(&#39;password&#39;).value != "" && m$(&#39;username&#39;).value != "") {

    var xmlhttp = createRequest();
    if (xmlhttp) {
     m$(&#39;loading&#39;).innerHTML = "<font color=&#39;red&#39;>loading...</font>";
     var username = m$(&#39;username&#39;).value;
     var pwd = m$(&#39;password&#39;).value;
     var code = m$(&#39;txtCode&#39;).value;
     var url = "dologin.php";
     xmlhttp.open("POST", url, true);
     xmlhttp.onreadystatechange = ValidateResult;
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     xmlhttp.send("username=" + escape(username) + "&password=" + escape(pwd) + "&code=" + escape(code));

    } else {
     alert(&#39;xmlHttp创建失败.&#39;);

    }

    function ValidateResult() {
     if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
       if (xmlhttp.responseText != "") {

        //window.alert(xmlhttp.responseText);
        var obj = eval("(" + xmlhttp.responseText + ")");
        if (obj.result == true) {
         alert("提示:" + obj.info);
         window.location = &#39;index.php&#39;;

        } else {
         alert("错误:" + obj.info);

        }
       } else {
        window.alert("从服务器获取失败");

        window.location.reload();
       }
       m$(&#39;loading&#39;).innerHTML = "";
      }
     }

    }


   }

  }

  function m$(id) {
   return document.getElementById(id);
  }

  function changeCode() {
   var xmlhttp = createRequest();
   if (xmlhttp) {
    m$(&#39;loading&#39;).innerHTML = "<font color=&#39;red&#39;>loading...</font>";
    var dt = new Date().getTime();
    // alert(dt);
    var url = "function/imagecode.php?dummay" + escape(dt);
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = ValidateResult;
    xmlhttp.send(null);

   } else {
    alert(&#39;xmlHttp创建失败.&#39;);

   }

   function ValidateResult() {
    if (xmlhttp.readyState == 4) {
     if (xmlhttp.status == 200) {
      var dt = new Date().getTime();
      var url = "function/imagecode.php?dummay" + escape(dt);
      m$(&#39;imgCode&#39;).src = "function/imagecode.php?dummay" + escape(dt);
      m$(&#39;loading&#39;).innerHTML = "";
     }
    }

   }
  }

  function showTool() {
   $(&#39;#pToolTip&#39;).css("display", "block");
  }

  function hideTool() {
   $(&#39;#pToolTip&#39;).css("display", "none");
  }
  window.onload = initPage;

  function initPage() {
   $(&#39;#pToolTip&#39;).css("display", "none");
  }
 </script>
 </head>
 <body>
 <p style="background-color:#2A3F55; height:80px;">
  
 </p>
 <p style="min-height:500px;">
  
  <p class="left">
  
  <p style="margin:120px auto auto auto; height:300px; text-align:left">
   <p style="font-size:26px;color:#2A3F55; text-align:center;">Ajax PHP Demo System
   <img src="Images/appstorm-icon.png" alt="appcation storm image" style="position:relative;top:-18px; left:-12px;         vertical-align:middle; text-align:center;font-size:10px; width:65px; height:46px;"/>
   </p>
   <br/>
   <hr style="border:dashed thin #2A3F55;width:70%; text-align:center;"/>
   <p style="font-size:13px;color:#999999; margin:20px auto 0 auto; padding-left:200px;">
   Author:<a href="#" onmousemove="showTool();" onmouseout="hideTool();">wangming</a>
   </p>
   <p style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">DateTime:2009-9-1</p>
   <p style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Version:1.0.0</p>
   <p style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Email:wangmingemail@163.com     </p>
   <p id="pToolTip">
   <img src="Images/ming.jpg" height="86px;"/>
   <span class="authordes">
    <br/>
    姓名:wangming<br/>
    电商06-2<br/>
   </span>
   
   </p>
   
  </p>
  
  </p>
  
  <p class="right">
  
  <form>
   <br/>
   <table class="flogin">
   <tr>
    <td>用户名:</td>
    <td><input type="text" name="username" id="username"/></td>
    <td></td>
   </tr>
   <tr>
    <td>密   码:</td>
    <td><input type="password" name="password" id="password" /></td>
    <td></td>
   </tr>
   <tr>
    <td>验证码:</td>
    <td>
    <input type="text" name="txtCode" id="txtCode" size="12" /> 
    <img src="function/imagecode.php" id="imgCode" alt="image code" height="22px;" style=" vertical-align:bottom;"/>
    </td>
    <td><input type="button" class="btnrefresh" onclick="changeCode();" /></td>
   </tr>
   <tr>
    <td></td>
    <td><input type="button" class="btnlogin" onclick="chkForm();" /></td>
    <td></td>
   </tr>
   <tr>
    <td></td>
    <td><span id="loading"></span></td>
    <td><span id="code"></span></td>
   </tr>
   
   </table>
  </form>
  </p>
  
 </p>
 <p style="background-color:#2A3F55; height:60px; margin:auto 0 0 0; clear:both; text-align:center; line-height:60px; color:#FFFFFF;font-size:12px;">
  ©Copyright 2015.
 </p>
 </body>
</html>
Copy after login

2 ajaxhelper.js

function createRequest() {
 try {
  request = new XMLHttpRequest();
 } catch (tryMS) {
  try {
   request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (otherMS) {
   try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (failed) {
    request = null;
   }
  }
 }
 return request;
}

function getActivatedObject(e) {
 var obj;
 if (!e) {
  // early version of IE
  obj = window.event.srcElement;
 } else if (e.srcElement) {
  // IE 7 or later
  obj = e.srcElement;
 } else {
  // DOM Level 2 browser
  obj = e.target;
 }
 return obj;
}

function addEventHandler(obj, eventName, handler) {
 if (document.attachEvent) {
  obj.attachEvent("on" + eventName, handler);
 } else if (document.addEventListener) {
  obj.addEventListener(eventName, handler, false);
 }
}
Copy after login

3 dologin .php

<?php
 session_start();
 header("Content-type:text/html;charset=gb2312");//防止返回的中文乱码
 $name=$_POST[&#39;username&#39;];
 $pwd=$_POST[&#39;password&#39;];
 $imagecode=$_POST[&#39;code&#39;];
 if(strtoupper($imagecode)==$_SESSION["code"])
 {
  include("conn/conn.php");
  $sql="select studentName,studentPwd from tbstudent where studentId=&#39;".$name."&#39;";
  $result=mysql_query($sql,$conn);
  if($row=mysql_fetch_assoc($result))
  {
   if($pwd==$row[&#39;studentPwd&#39;])
   {
   $_SESSION[&#39;username&#39;]=$row[&#39;studentName&#39;];
   //echo "{&#39;result&#39;:true,&#39;info&#39;:&#39;登陆成功!&#39;,&#39;code&#39;:&#39;".$_SESSION["code"]."&#39;}";
   echo "{&#39;result&#39;:true,&#39;info&#39;:&#39;登陆成功!&#39;}";
   
   }
   else
   {
   echo "{&#39;result&#39;:false,&#39;info&#39;:&#39;密码错误!&#39;}";
   }
  }
  else
  {
   echo "{&#39;result&#39;:false,&#39;info&#39;:&#39;该用户不存在!&#39;}";
  }
 }
 else
 {
  echo "{&#39;result&#39;:false,&#39;info&#39;:&#39;验证码错误!&#39;}";
 }
?>
Copy after login

4 conn.php

<?php
 $conn=$mysql_connect("localhost","root", "");
 mysql_select_db("bbs",$conn);
 mysql_query("SET NAMES GB2312");
 ?>
 5
 <?php
class Users {
 function Users() {
 }
 function checkLogin($username, $userpwd) {
  try {
   mysql_connect("localhost", "root", "123");
   mysql_select_db("studentdb");
   mysql_query("SET NAMES GB2312");
   $sql = "select userid from tbuser where username=&#39;$username&#39; and userpwd=&#39;" . md5(trim($userpwd)) . "&#39;";
   $result = mysql_query($sql);
   if ($result) {
    $arr = mysql_fetch_row($result);
    $uid = $arr[0];
    if ($uid != "") {
     return "true|$uid login ok.$sql";
     mysql_close();
    } else {
     return "false|login failed!$sql";
     mysql_close();
    }
   } else {
    return "false|$result link db failed!";
    mysql_close();
   }
  }
  catch(Exception $ex) {
   return "false|$ex";
   mysql_close();
  }
 }
 function AddUser($name, $pwd) {
  try {
   mysql_connect("localhost", "root", "123");
   mysql_select_db("studentdb");
   mysql_query("set names gb2312");
   $sql0 = mysql_query("select userid from tbuser where username=&#39;$name&#39;");
   $info0 = mysql_fetch_array($sql0);
   $userid = $info0[0];
   if ($info0 != false) {
    return "false | $name is exisis.(id:$userid)";
   }
   $pwd = md5(trim($pwd));
   $query = mysql_query("insert into tbuser(username,userpwd)values(&#39;$name&#39;,&#39;$pwd&#39;)");
   $error = mysql_errno();
   if ($query) {
    return "true | add ok";
   } else {
    return "false | $error";
   }
  }
  catch(Exception $ex) {
   return "false | $ex";
  }
 }
 function DeleteUser($name) {
  mysql_connect("localhost", "root", "123");
  mysql_select_db("studentdb");
  mysql_query("set names gb2312");
  $name = trim($name);
  $sql0 = mysql_query("select userid from tbuser where username=&#39;$name&#39;");
  $info0 = mysql_fetch_array($sql0);
  if ($info0 != false) {
   if (mysql_query("delete from tbuser where username=&#39;$name&#39;")) {
    return "true | delete ok.(id:" . $info0[0] . ")";
   } else {
    return "false | 删除失败";
   }
  } else {
   return "false | 删除失败 $name 不存在";
  }
 }
 function UpdateUser($id, $name, $pwd) {
  if (is_numeric(intval(trim($id)))) {
   if ($id && $name && $pwd) {
    mysql_connect("localhost", "root", "123");
    mysql_select_db("studentdb");
    mysql_query("set names gb2312");
    $pwd = md5(trim($pwd));
    $isexists = mysql_query("select * from tbuser where userid=&#39;$id&#39;");
    if (mysql_fetch_array($isexists)) {
     $sql0 = mysql_query("update tbuser set username=&#39;$name&#39;,userpwd=&#39;$pwd&#39; where userid= $id");
     if ($sql0) {
      return "ture | update ok";
     } else {
      return "false | 更新失败";
     }
    } else {
     return "false | usrid=$id not exists.";
    }
   } else {
    return "false |id=$id name=$name and pwd=$pwd .At least one of them is null.";
   }
  } else {
   return "false | $id is not type of int.";
  }
 }
}
?>
Copy after login

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Detailed explanation of infinite classification tree data formatting code example

PHP obtains N-level classification from a two-dimensional array Tree implementation method

php fseek implementation function two ways to read large files

The above is the detailed content of How to write PHP login function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

See all articles