PHP session and cookie implementation of automatic login

Source: Internet
Author: User
Tags php session set cookie setcookie trim valid root directory

Use of Session:

Session_Start (); Defines the $_session array variable.

Session_Start () cannot have any form of output prior to use, including PHP output and HTML code.

$_session arrays cannot use numeric subscripts, only string subscripts can be used.

The Session_save_path configuration entry in php.ini determines where the session is saved.

By default, the session is saved in a file. We can use the Session_set_save_handler () function to rewrite the session mechanism.

Set valid time

The code is as follows
Ini_set (' Session.gc_maxlifetime ', 24*3600);//session Save one day
Session_Start ();
$_session[' web_name ']= ' NetEase ';

Description: As if the default is the time is: 20-24 minutes, but close the browser session will automatically disappear!

Delete session:

Deletes an element unset ($_session[key]);

Delete all session $_session=array ();

Deletes the file that holds the session data Session_destroy ();

The Session_distroy () method simply deletes the server-side session file and does not release the $_session variable in memory, if we var_dump ($_session) immediately after Session_distroy (), You can still see the session output. Therefore, if you want to completely release session, you must use $_session=array ().

Use of cookies:

Set Cookie:setcookie (variable name, variable value, life time (timestamp)).

Delete Cookie:setcookie (variable name, value, Time ()-1). Rationale: Set the cookie's lifetime to expire.

Read cookie:$_cookie[variable name].

$path = "/"; Set the path where the cookie is stored; 1. The default storage is this directory, only in this directory to access, 2. " /"The representation 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); /* Valid for 1 days * *

Note: Cookies can hold values that are only string types, but how do I fix them?


The code is as follows

$array =array (' A ', ' B ');
The "Serialize:" Return value is a string. Sometimes in order to put some data into a string to save, but want to keep the data original structure and content. You need to use this function.
$res =serialize ($array);
Setcookie ("Snsresult", $res, Time () +intval (24*3600));


The code is as follows

Recovering Serialize objects

$other = stripslashes ($_cookie[' snsresult ');/must perform this step
$arr =unserialize ($other);//First decode the encrypted cookie

Note: Setcookie is not allowed to output any content before it is accessed in code, nor can empty rows, otherwise cookies are not valued.

1, $_cookie can only read the value of cookies, and can not set the cookie.

2. You cannot have any type of output before using Setcookie.

3, after the first time the script set cookies, it is not in the current script to use $_cookie to get. You need to refresh the page or get it in another script.

Automatic Login

The code is as follows

Check if the user is logged on

Function Checklogin () {  
     if (Empty ($_session[' user_info ')) {     Check if the session is empty   
     if (Empty ($_cookie[' username ')) | | empty ($_ cookie[' password ']) { //If the session is empty, and the user does not choose to record a login-like   
     Header ("Location : login.php?req_url= ". $_server[' Request_uri ']); //Go to login page, record request URL, jump past after login, user experience is good.  &NBSP
}else{  //The user has chosen to remember the login status   
     $user = GetUserInfo ($_ cookie[' username '],$_cookie[' password '];  //access to the user's profile   
     if ( Empty ($user)) {   //username password not to get information, go to the login page   
     Header ("location:login.php?req_url=". $_server[' Request_uri ');   
    }else{  &NBSP
     $_session[' user_info '] = $user;  /username and password right, Put the user's personal data into the session   
    }  &NBSP

Two, the user submits the 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 = "Incorrect authentication code";   
}elseif ($username = = ' | | $password = = ') {  &NBSP
$err _msg = "User name and password cannot be null";   
$row = GetUserInfo ($username, $password); NBSP;&NBSP
if (empty ($row)) {  
$err _msg = "Incorrect username and password";   
$_session[' user_info '] = $row;   
if (!empty ($remember)) {    // If the user chooses, record the login status and place the username and password in the cookie   
Setcookie ("username", $username, Time () +3600*24*365);  &NBSP
Setcookie ("Password", $password, Time () +3600*24*365);   
if (Strpos ($ref _url, "login.php") = = False) {  
Header ("Location:". $ref _url);  
Header ("location:main_user.php");   

Third, when the user point exits, clear the record login status

Exit Login

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:


Both are used as conversational techniques to address the stateless nature of HTTP.

The SessionID is stored in a cookie. By default, the session is dependent on cookies, and if the browser-side has completely disabled cookies, the session will not work. But we have other ways to keep the session useful. For example, URL rewrite, put SessionID in the URL, add hidden fields to the form, speak SessionID in hidden fields, send to the browser.


Cookies Save the early browser side, each time access to the server, will tell the cookie to take the past, to ensure that the server know two requests from the same client. Low security.

The session is saved on the server, and each request is sessionid to the server by the cookie. High security.

The session is valid from Session_Start () to the end of the browser shutdown.

Cookies can be set for an expiration date. The default is the browser shutdown cookie is invalid, SessionID lost, even if the server side of the session file is still, will not be found.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.