search
HomeBackend DevelopmentPHP TutorialUse PHP to realize automatic login storage mechanism within a week

This article mainly introduces the use of PHP to realize automatic login storage mechanism (cookie, session, localStorage) within a week, which can achieve free login within a week. Interested friends can refer to it.

Cookie, session, and localStorage should be the three most troublesome for programmers. I will use the username and password of the simple login interface to explain.

1. Cookies are used to store user-related data. The storage location is local to the user:

The first is the login interface definition:

<form action="server.php" method="post"> 
        <input type="text" name="username" class="username" placeholder="Username"> 
        <input type="password" name="password" class="password" placeholder="Password"> 
        <button type="submit">Sign me in</button> 
        <p class="error"><span>+</span></p> 
      </form>

Everyone knows the above code, it is a form. Then it is the action server.php server processing,

<?php 
/** 
 * Created by PhpStorm. 
 * User: Administrator 
 * Date: 2016-7-19 
 * Time: 11:50 
 */ 
include "data.php"; 
header("Content-type:text/html;charset=utf-8"); 
//echo "ddd"; 
if ($_SERVER["REQUEST_METHOD"] == "POST") {//第一步 
//  echo "ddd1"; 
  if ($_POST["username"] == $info["username"] && $_POST["password"] == $info["password"]) {//第二步 
    $myArr = $_POST; 
    $myArr = array_merge($myArr, array("loginIP" => $_SERVER["REMOTE_ADDR"], "loginTime" => time())); 
    se($myArr); 
    setcookies($_POST["username"], $_POST["password"]); 
    setStroage($_POST["username"], $_POST["password"]); 
    echo "<script> 
   window.location.href=&#39;index.php&#39;; 
  </script>"; 
  } 
} else { 
  echo "<script> 
alert(&#39;请登录&#39;); 
window.location.href=&#39;login.html&#39;; 
</script>"; 
} 
//通过session保存到服务器 
function se(array $arr) 
{ 
  session_start(); 
  $_SESSION["username"] = $arr["username"]; 
  $_SESSION["password"] = $arr["password"]; 
  $_SESSION["loginIP"] = $arr["loginIP"]; 
  $_SESSION["loginTime"] = $arr["loginTime"]; 
} 
//通过cookie保存到本地 
function setCookies($username, $password) 
{ 
  setcookie("username", $username, time() + 120); 
  setcookie("password", $password, time() + 120); 
} 
 
//echo "<script> 
// 
//  localStorage.setItem(&#39;username&#39;,&#39;$username&#39;); 
//localStorage.setItem(&#39;password&#39;," . "&#39;" . $password . "&#39;" . "); 
//</script>"; 
function setStroage($username, $password){ 
  echo "<script> 
  localStorage.setItem(&#39;username&#39;," . "&#39;" . $username . "&#39;" . "); 
  localStorage.setItem(&#39;password&#39;," . "&#39;" . $password . "&#39;" . "); 
  </script>"; 
}

is loaded with a data.php actually contains a piece of data,

$info=array("username"=>"admin","password"=>"admin");

This data is mainly used to check whether the entered user name and password are correct.

First of all, in the server, judge whether it is a post request. If not, you will be prompted to log in again and return to the login interface. After confirming that it is a post, you will then judge whether the information is entered correctly. If it is correct, set the cookie. The following code Let me explain one by one

$myArr = $_POST;//把post传过来的数据放在myarr;里面 
    $myArr = array_merge($myArr, array("loginIP" => $_SERVER["REMOTE_ADDR"], "loginTime" => time()));//这是穿的另外两个参数,一个是用户登录地址,另一个是cookie存活时间(会在寻获时间以为消失) 
    se($myArr); 
    setcookies($_POST["username"], $_POST["password"]);//这个是设置cookie,把传过来的两个值设置成cookie,会有一个getCookie进行接收 
    setStroage($_POST["username"], $_POST["password"]); 
    echo "<script> 
  window.location.href=&#39;index.php&#39;;

In fact, at this time the cookie has been stored according to the time we set, and then what we need to do is the login-free function , the processing of the background server, just like when we log in to other software, we will be prompted to waive the login password within a week.

is the following code:

function intialLoadInfo(){ 
    $("input:text").val(getCoolieByKey("username"));//这两个就是吧下面获取的之前输入过的用户名和密码进行自动填写(实现目的) 
    $("input:password").val(getCoolieByKey("password")); 
  } 
  //通过key值获取cookie 
  function getCoolieByKey(key){ 
    var cookie=document.cookie.split(";");//这行代码是吧cookie的值进行分离(split),以便于下面遍历(分离后就是一个数组一样) 
    for(var i=0;i<cookie.length;i++){//遍历长度 
      var value=cookie[i].trim();//去掉空格 
      if (value.indexOf(key)==0){//判断是不是第一个值 
        val=value.split("="); 
        console.log(val[0]); 
        return val[1]; 
      } 
    } 
  }

The first method above executes getCookieByKey(key);

The parameter received by this function with parameters is the myArr data we encapsulated above;

The detailed explanation is in the code, you can refer to it.

2.session:session is used to store user information on the server side. When the browser is closed, it will be automatically destroyed;

session_start();

The super array $_SESSION can realize the setting and reading of session;

The code is as follows:

function se(array $arr) 
{ 
  session_start(); 
  $_SESSION["username"] = $arr["username"]; 
  $_SESSION["password"] = $arr["password"]; 
  $_SESSION["loginIP"] = $arr["loginIP"]; 
  $_SESSION["loginTime"] = $arr["loginTime"]; 
}

First of all, we will use the above code, which also obtains four attributes and puts them in our $_SESSION; store them:

Then the above code, you can see there is a se

$myArr = array_merge($myArr, array("loginIP" => $_SERVER["REMOTE_ADDR"], "loginTime" => time()));//这是穿的另外两个参数,一个是用户登录地址,另一个是cookie存活时间(会在寻获时间以为消失) 
    se($myArr);

This is written for session;

It mainly stores four attributes, username.password.IP.time

It is also commented in the above code; in fact, now we can check the session we created in the session.

3. LocalStorage on the JS side: the local storage method provided by HTML5 (can be called a "key-value pair" database);

Set data: localStorage.setItem(" key","value");
Read data: localStorage.getItem("key");The read result is a string;
Delete data: localStorage.removeItem("key");

The detailed code is as follows:

The js file written under the html is Then it is the implementation:

$(function (){ 
    if (localStorage.getItem("username")!=""&&localStorage.getItem("password")!=""){ 
      document.getElementById("username").value=localStorage.getItem("username"); 
      document.getElementById("password").value=localStorage.getItem("password"); 
 
    } 
  });

This function is mainly to create the

function setStroage($username, $password){ 
  echo "<script> 
  localStorage.setItem(&#39;username&#39;," . "&#39;" . $username . "&#39;" . "); 
  localStorage.setItem(&#39;password&#39;," . "&#39;" . $password . "&#39;" . "); 
  </script>"; 
}

created with php. The above is the entire content of this article. I hope it will be helpful to everyone’s study. .


Related recommendations:

How to delete files in the directory using PHP unlink and rmdir

PHP Detailed explanation of commonly used methods for mysqli transaction operations

PHP uses asterisks to replace some characters in the user name, mobile phone and email address

The above is the detailed content of Use PHP to realize automatic login storage mechanism within a week. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.