Use PHP to implement automatic login storage mechanism (cookie, session, Localstorage) _php instance within one week

Source: Internet
Author: User
Tags button type php server setcookie

Cookies, session, Localstorage these three should be the most headaches for programmers, I use the simple login interface username and password to explain it.

1.cookie is used to store user-related data and store location in user's Local:

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> 
        <div "error" class= ></div> 
      </form> 

The above code everybody knows, is a form. Then the action server.php server is processed,

<?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") {//First step//echo "DDD1"; if ($_post["username"] = = $info ["username"] && $_post["password"] = = $info ["password"]) {//Step two $MYARR = $_pos 
    T 
    $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= ' index.php '; 
  </script> "; 
} else {echo <script> alert (' Please login '); 
window.location.href= ' login.html '; 
</script> "; 
  ///session saved to server function se (array $arr) {session_start (); 
  $_session["username"] = $arr ["username"]; 
  $_session["password"] = $arr ["Password"]; $_session["LoginiP "] = $arr [" Loginip "]; 
$_session["logintime"] = $arr ["Logintime"]; 
  ///save via cookie to local function setcookies ($username, $password) {Setcookie ("username", $username, Time () + 120); 
Setcookie ("Password", $password, Time () + 120); 
}//echo "<script>///Localstorage.setitem (' username ', ' $username '); Localstorage.setitem (' Password ', ".) "'" . $password. 
"'" . "); 
</script> "; function Setstroage ($username, $password) {echo <script> localstorage.setitem (' username ', ". "'" . $username. 
  "'" . "); Localstorage.setitem (' Password ', ".) "'" . $password. 
  "'" . "); 
</script> "; 
 }

It's loaded with a data.php, which is actually a piece of data,

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

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

First in the server is not the judge is not the POST request, if not prompted to log on again, return to the login interface, determine is post, and then to determine whether the information is correct, if the correct setcookie. The following code I one by one explain

$MYARR = $_post;//The data passed from POST to Myarr 
    $myArr = Array_merge ($MYARR, Array ("Loginip" => $_server["REMOTE_ADDR") ], "Logintime" => Time ());//This is the other two parameters worn, one is the user login address and the other is the cookie lifetime (which disappears in the time it is found) 
    SE ($MYARR); 
    Setcookies ($_post["username"], $_post["password");//This is a cookie, set the pass two values to a cookie, there will be a getcookie to receive 
    Setstroage ($_post["username"], $_post["password"]); 
    echo "<script> 
  window.location.href= ' index.php '; 

In fact, cookies have been set by the time we have stored down, and then we have to do is no login function, the processing of the backend server, as we log on to other software, will be prompted a week without landing password,

is the following code:

function Intialloadinfo () { 
    $ ("Input:text"). Val (Getcooliebykey ("username"))//These two are. The user name and password entered before are automatically filled in ( Implementation Purpose) 
    $ ("Input:password"). Val (Getcooliebykey ("password")); 
  Gets 
  the cookie function Getcooliebykey (key) { 
    var cookie=document.cookie.split (";") through the key value; /This line of code is to separate the value of the cookie (split) so that the following traversal (like an array after separation) for 
    (Var i=0;i<cookie.length;i++) {//Traversal length 
      var value= Cookie[i].trim ()//Remove Space 
      if (Value.indexof (key) ==0) {//judgment is not the first value 
        val=value.split ("="); 
        Console.log (Val[0]); 
        return val[1];}} 
   

The first method above executes Getcookiebykey (key);

The parameters of this function receive the parameter is the Myarr data we have encapsulated above;

Then the detailed explanation is in the code, we can refer to.

2.session:session is used to store user information on the server side, which is automatically destroyed when the browser closes;

Session_Start ();

Super Array $_session can be set up and read in 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, the above code, the same is to get four attributes, put into our $_session, stored down:

And then there's the code, and you can see that there's an SE

$MYARR = Array_merge ($MYARR, Array ("Loginip" => $_server["REMOTE_ADDR"], "Logintime" => Time ());//This is the other two parameters to wear, One is the user's login address and the other is the cookie's survival time (which disappears in the time it is found) 
    SE ($MYARR); 

Here is for the session to write;

He mainly stores four attributes, Username.password.IP.time

The above code is also commented; in fact, we can now find our own session in the session.

The local storage mode provided by the 3.JS LOCALSTORAGE:HTML5 (can be called "key value pair" database);

Set data: Localstorage.setitem ("Key", "value");
Read data: Localstorage.getitem ("key"); Read the result is a string;
Delete data: Localstorage.removeitem ("key");

The detailed code is as follows:

The JS file written underneath the HTML is then implemented:

$ (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 primarily created with PHP

function Setstroage ($username, $password) { 
  echo <script> 
  localstorage.setitem (' username ', ". "'" . $username. "'" . "); 
  Localstorage.setitem (' Password ', ".) "'" . $password. "'" . "); 
  </script> "; 

In fact, this thing needs to write slowly, although I can write out, but each time use to refer to this example, so I hope that I used a long time omnipotent examples for everyone useful, thank you for reading, hope to help everyone, thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.