


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!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
