Automatically log on to the session and cookie in php

Source: Internet
Author: User
Tags sessions set cookie setcookie trim

Session usage:

Session_start (); defines the $ _ SESSION array variable.

Session_start () cannot be output in any form, including the output and html code in php.

The $ _ SESSION array cannot use numeric subscript, but can only use string subscript.

The session_save_path configuration item in php. ini determines the session storage location.

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

Set effective time

The code is as follows: Copy code
Ini_set ('session. Gc_maxlifetime', 24*3600); // The session is saved for one day.
Session_start ();
$ _ SESSION ['web _ name'] = 'netease ';

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

Delete session:

Delete an element unset ($ _ SESSION [key]);

Delete all sessions $ _ session = array ();

Delete session_destroy ();

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

Cookie usage:

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

Delete cookie: setcookie (variable name, value, time ()-1 ). Principle: Set the cookie expiration time.

Read cookie: $ _ COOKIE [variable name].

$ Path = "/"; // Set the cookie storage path; 1. it is stored in the local directory by default and can only be accessed in this directory. 2. "/" indicates that it is stored in the root directory. 3. "/foo/" is accessible only to files in the foo folder.

The code is as follows: Copy code

Setcookie ("cookiename", "NetEase", time () + intval (24*3600), $ path);/* valid for 1 day */

Note: The cookie can only be stored in the string type, but how can this problem be solved!


The code is as follows: Copy code

$ Array = array ('A', 'B ');
// "Serialize:" the returned value is a string. Sometimes, in order to convert some data into strings, we hope to keep the original data structure and content. This function is required.
$ Res = serialize ($ array );
Setcookie ("snsresult", $ res, time () + intval (24*3600 ));


The code is as follows: Copy code

// Restore the serialize object

$ Other = StripSlashes ($ _ COOKIE ['sresult']); // This step must be performed
$ Arr = unserialize ($ other); // decodes the encrypted cookie

Note: When setcookie accesses a value in the code, it cannot output any content or empty rows. Otherwise, the cookie has no value.

1. $ _ COOKIE can only read the cookie value and cannot be set.

2. There cannot be any type of output before setcookie is used.

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

Automatic logon

The code is as follows: Copy code

// Check whether the user logs on

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, the user does not select to log on.
Header ("location: login. php? Req_url = ". $ _ SERVER ['request _ URI ']); // go to the logon page and record the REQUEST url. After logging on, go to the logon page. The user experience is good.
} Else {// Remember the logon status
$ User = getUserInfo ($ _ COOKIE ['username'], $ _ COOKIE ['password']); // retrieves the user's personal data
If (empty ($ user) {// if the user name and password are incorrect, the information is not obtained. Go to to the logon page.
Header ("location: login. php? Req_url = ". $ _ SERVER ['request _ URI ']);
} Else {
$ _ SESSION ['User _ info'] = $ user; // The user name and password are correct. Put the user's personal data in the session.

2. The user submits logon 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 verification code ";
} Elseif ($ username = ''| $ password = ''){
$ Err_msg = "neither user name nor password can be blank ";
} Else {
$ Row = getUserInfo ($ username, $ password );
If (empty ($ row )){
$ Err_msg = "the user name and password are incorrect ";
} Else {
$ _ SESSION ['User _ info'] = $ row;
If (! Empty ($ remember) {// if the user chooses to log on, the user name and password added are recorded 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 points out, the logon status is cleared.

// 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 are as follows:


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

SessionID is saved in the cookie. By default, the session depends on the cookie. If the cookie is completely disabled on the browser side, the session cannot be used. However, we have other methods to make the session continue to be useful. For example, if you rewrite a url, place the sessionID in the url, add a hidden field to the form, store the sessionID in the hidden field, and send it to the browser.


The cookie is stored on the browser end early. Every time you access the server, the cookie will be taken over to ensure that the server knows that the two requests come from the same client. Low security.

The session is stored on the server. Each request matches the server with the sessionID of the cookie. High security.

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

Cookie can set the validity period. By default, the cookie is disabled by the browser, and the sessionID is lost. Even if the session file on the server is still present, it is not 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.