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='index.php'; </script>"; } } else { echo "<script> alert('请登录'); window.location.href='login.html'; </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('username','$username'); //localStorage.setItem('password'," . "'" . $password . "'" . "); //</script>"; function setStroage($username, $password){ echo "<script> localStorage.setItem('username'," . "'" . $username . "'" . "); localStorage.setItem('password'," . "'" . $password . "'" . "); </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='index.php';
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('username'," . "'" . $username . "'" . "); localStorage.setItem('password'," . "'" . $password . "'" . "); </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!