Home  >  Article  >  Backend Development  >  Automatic login using session and cookie in php_PHP tutorial

Automatic login using session and cookie in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:36:451027browse

Use of session:

session_start(); Define $_SESSION array variable.

Before session_start() is used, there cannot be any form of output, including output in php and html code.

 The $_SESSION array cannot use numeric subscripts, only string subscripts.

The session_save_path configuration item in php.ini determines the location where the session is saved.

By default, sessions are saved in files. We can use the session_set_save_handler() function to rewrite the session mechanism.

Set valid time

 代码如下  
SESSION:
ini_set('session.gc_maxlifetime',24*3600);//session保存一天
session_start();
$_SESSION[‘web_name’]='网易';

Note: It seems that the default time is: 20-24 minutes, but the session disappears automatically when the browser is closed!

Delete session:

Delete an element unset($_SESSION[key]);

Delete all sessions $_SESSION=array();

Delete the file that saves session data session_destroy();

The session_disstroy() method only deletes the session file on the server side and does not release the $_SESSION variable in the memory. If we var_dump($_SESSION) immediately after session_distroy(), we can still see the session output. Therefore, if you want to completely release the session, you must use $_SESSION=array().

Use of cookies:

Set cookie: setcookie (variable name, variable value, survival time (timestamp)).

Delete cookies: setcookie(variable name, value, time()-1). Principle: Set the cookie's lifetime to expire.

Read cookie: $_COOKIE[variable name].

$path="/"; //Set the path for cookie storage; 1. The default storage is this directory, which can only be accessed in this directory. 2. "/" means it is stored in the root directory, 3. "/foo/ "Only files under the foo folder can be accessed

The code is as follows


setcookie("cookiename","NetEase'", time()+intval(24*3600),$path); /* Validity period 1 day */

 代码如下  


setcookie("cookiename","网易'", time()+intval(24*3600),$path); /* 有效期 1天 */

Note: The value stored in the cookie can only be of string type, but how to solve the problem of storing numerical values!

Storage:

The code is as follows

$array=array('a',' b');
//"serialize:"The return value is a string. Sometimes, in order to convert some data into a string and store it, we want to keep the original structure and content of the data. You need to use this function.
$res=serialize($array);
setcookie("snsresult",$res,time()+intval(24*3600));

 代码如下  

$array=array('a','b');
//"serialize:"返回值是一个字符串。有的时候为了把一些数据转为字符串存起来,但是希望保持数据原来有结构和内容。就要用到这个函数。
$res=serialize($array);
setcookie("snsresult",$res,time()+intval(24*3600));

Reading:

The code is as follows

//Restore serialize object

 代码如下  

//恢复serialize对象

 $other = StripSlashes($_COOKIE['snsresult']);//必须执行这步
  $arr=unserialize($other);//先将加密cookie进行解码 www.111Cn.net

$other = StripSlashes($_COOKIE['snsresult ']);//This step must be performed
$arr=unserialize($other);//Decode the encrypted cookie first www.111Cn.net

Note: When accessing the value of setcookie in the code, you cannot output any content in front of it, nor can it be a blank line, otherwise the cookie will have no value.

1. $_COOKIE can only read the value of the cookie and cannot set the cookie.

2. Before using setcookie, there cannot be any type of output.

3. After the script sets the cookie for the first time, it cannot be obtained by using $_COOKIE in the current script. You need to refresh the page or obtain it in other scripts.

Automatic login

The code is as follows

//Check if the user is logged in


function checklogin(){
If(empty($_SESSION['user_info'])){ //Check whether the session is empty
If(empty($_COOKIE['username']) || empty($_COOKIE['password'])){ //If the session is empty and the user does not choose to record the login status
header("location:login.php?req_url=".$_SERVER['REQUEST_URI']); //Go to the login page, record the requested url, and jump to it after logging in. The user experience is good.
}else{ //The user chose to remember login status
$user = getUserInfo($_COOKIE['username'],$_COOKIE['password']); //Get the user's personal information
If(empty($user)){ //The username and password are incorrect and the information is not retrieved. www.111Cn.net Go to the login page
header("location:login.php?req_url=".$_SERVER['REQUEST_URI']);
}else{
$_SESSION['user_info'] = $user; //The username and password are correct, put the user's personal information in the session
}  
}  
}  
}


2. User submits login information


username = trim($_POST['username']);
$password = md5(trim($_POST['password']));
$validatecode = $_POST['validateCode'];
$ref_url = $_GET['req_url'];
$remember = $_POST['remember'];

$err_msg = '';
if($validatecode!=$_SESSION['checksum']){
$err_msg = "Verification code is incorrect";
}elseif($username=='' || $password==''){
$err_msg = "Username and password cannot be empty";
}else{
$row = getUserInfo($username,$password);

if(empty($row)){
$err_msg = "Both username and password are incorrect";
}else{
$_SESSION['user_info'] = $row;
if(!empty($remember)){ //If the user chooses, record the login status and put the username and encrypted password in the cookie
setcookie("username", $username, time()+3600*24*365);
setcookie("password", $password, time()+3600*24*365);
}
if(strpos($ref_url,"login.php") === false){
header("location:".$ref_url);
}else{
header("location:main_user.php");
}
}
}


3. When the user clicks to exit, clear the recorded login status


//Log out


function logout(){
unset($_SESSION['user_info']);
if(!empty($_COOKIE['username']) || !empty($_COOKIE['password'])){
setcookie("username", null, time()-3600*24*365);
setcookie("password", null, time()-3600*24*365);
}
}

The connection and difference between the two:

Contact:

Both are called session technologies and are used to solve the stateless nature of http.

SessionID is stored in cookie. By default, the session relies on cookies. If cookies are completely disabled on the browser, the session will not be available. But we have other ways to keep the session useful. For example, in url rewriting, put the session ID in the url; add a hidden field to the form, store the session ID in the hidden field, and send it to the browser.

Difference:

The cookie is saved early in the browser. Every time you access the server, the cookie will be brought to the server to ensure that the server knows that the two requests come from the same client. Less secure.

The session is saved on the server, and each request will be matched by the session ID brought by the cookie to the server. Higher security.

The validity period of the session starts from session_start() and ends when the browser is closed.

Cookies can be set to expire. By default, if the browser closes the cookie, it will become invalid and the session ID will be lost. Even if the session file on the server side is still there, it will not be found.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/737680.htmlTechArticleUsage of session: session_start(); Define $_SESSION array variable. Before session_start() is used, there cannot be any form of output, including output in php and html code. The $_SESSION array does not...
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