In-depth understanding of Session and Cookie in PHP

Source: Internet
Author: User
This article provides a detailed analysis of Session and Cookie in PHP. For more information, see

This article provides a detailed analysis of Session and Cookie in PHP. For more information, see

When setting a cookie on a page, you must refresh or go to the next page to use $ _ COOKIE to get the variable value.
The reason is that when the page is accessed and loaded by the browser for the first time, the cookie in the page will be set and sent to the storage location specified by the client, therefore, $ _ COOKIE does not receive the value of the cookie variable sent from the client. When it is refreshed or to the next page, the client will run the page program on the server before, send the cookie corresponding to this address to the server, so $ _ COOKIE can get the value! To put it bluntly, when each page is accessed, if the client finds the cookie corresponding to the access address, it will send the cookie to the server before the program runs on the server. (my opinion on this)
I am not competent to express myself. If you have any questions, please be sorry!

When setting the cookie array in php, you cannot add data like the one in php:

The Code is as follows:


Setcookie ('My _ cookie [] ', 1 );
Setcookie ('My _ cookie [] ', 2 );
Print_r ($ _ COOKIE); // Array ([my_cookie] => Array ([0] => 1 ))
// The array value is successfully added, but the index is not changed. The subsequent data overwrites the previous data!
Therefore
My_cookie [] indicates the location of the first element of the data by default, that is, the index is
0. Note that it is different from php! Remember to specify an array element index for future cookie data!

$ My_cookie [] = 1;
$ My_cookie [] = 2;
Print_r ($ my_cookie); // Array ([0] => 1 [1] => 2)
?>


Two methods to delete cookie variables:
1. php

The Code is as follows:


Setcookie ('user _ name_1 ', 'zhaofei299', time () + 3600); // The lifetime is 1 hour.
Setcookie ('user _ name_2 ', 'zhaofei299', time () + 3600); // The lifetime is 1 hour.
?>


2. php

The Code is as follows:


Setcookie ('user _ name_1 '); // The first type
Setcookie ('user _ name_2 ', "", time ()-1); // second
Print_r ($ _ COOKIE); // refresh page 2 and above will output Array ([user_name_1] =>)

/* Why user_name_1 in the super global variable $ _ COOKIE is not deleted (if the variable is empty, it does not mean it does not exist), and
User_name_2 deleted? That's because the two methods for deleting variables are different!
First, it sets the cookie survival period, except that its value is set to null by default, and the lifetime is the same as that of the browser.
When it is disabled, the cookie will be deleted! So when you open a new browser and output the address, you will find that all cookie variables are deleted!
Comment out the two setcookie () functions in 2.php (output the address again )!
Second, the cookie life cycle is also set, which means that the cookie life cycle will expire, and the cookie will be deleted.
On the New Page, when the client sends a cookie to the server, $ _ COOKIE does not get the value of this cookie variable!
*/
?>


The session id is stored in the client Cookie by default!

The Code is as follows:


Session_start ();
Print_r ($ _ COOKIE );
?>


There are two methods to set cookie:
Header ('set-cookie: user = zhaofei299 ');
Setcookie ('user', 'zhaofei299 ');
Session variables cannot be overloaded by GET or POST data!
The session variable is used to pass the array. The object does not need to be serialized!
When the session variable is used to pass an object, the class object definition and deserialization must be included before session_start () is called.
(Serialize) is also true!
You can use unset ($ _ SESSION ['***']) to delete a single SESSION variable!
Unset ($ _ SESSION) cannot be used to delete all SESSION variables, because this will delete all SESSION information. The Hong Kong virtual host, including
In PHPSESSID, the U.S. server, that is, the SESSION connection between the two pages is broken. use $ _ SESSION = array ();
Eliminates session IDs and disconnects pages!
Session_destroy ();
Procedure 1.1

The Code is as follows:


Session_start ();
Header ('content-type: text/html; charset = UTF-8 ');
$ _ SESSION ['a'] = 'a ';
$ _ SESSION ['B'] = 'B ';
Unset ($ _ SESSION); // after testing, comment it out.
$ _ SESSION ['user'] = 'zhaofei299 ';
Echo 'session _ ID: '. session_id ().'
';
Echo 'test test ';
?>


The Code is as follows:


Session_start ();
Echo $ _ SESSION ['user'];
Echo session_id (); // The session variable is changed.
?>


Session id (session_id) is transmitted in two ways:
1. cookie
2. url
Because the default session is cookie-based, and the cookie is sent with the http protocol, like the cookie
No output is available before session_start!
Now let's talk about the second method: Passing session IDs through URLs
The SID constant has been defined in php to get the session id.
Use of sesssin_id!

The Code is as follows:


Session_start ();
Echo defined ('sid ')? 'True': 'false'; // true
Echo SID; // nothing?
?>


Why is the SID value null? Is there a problem with it?
The reason is that the session is cookie-based by default, and the SID only uses session_id through the url
The value is assigned only when data is transferred!
Disable the cookie in the browser, and you will find that the SID has been output, the Hong Kong virtual host, instead of null!
Delete session
Three steps are required.

The Code is as follows:


Session_destroy (); // Step 1: Delete the session file on the server.
Setcookie (session_name (), '', time ()-3600); // Step 2: delete the actual session:
$ _ SESSION = array (); // Step 3: delete the $ _ SESSION global variable array
?>


We all know that the session variable is saved on the server, that is, the session variable is saved in a directory on the server.
You can find the address saved in the session file in session. save_path in php. ini.

The default session lifetime ends when browsing is disabled, but you must know that after the session expires, when the page session_start () is opened
Determine whether the session id exists. If it does not exist, create one. Otherwise, load the session id variable to the page! Because session_id will expire
A new session file is created, but it is not deleted (close the browser and open the session file to save
So use the session_destory () function to clear the session id and the corresponding session file.
Thoroughly cleared!

When session_id uses a url to pass session variable data, the session id is stored because session_start () is used to start the session.
Create a session id if it does not exist. Otherwise, load the session id variable to the page!

However, the session_id is passed through the url. However, a session id is generated every time the page is refreshed or accessed
You cannot get the session_id variable set on another page, so using session makes no sense!

Solution: Before session_start (), manually set the session_id of the page so that the page can get
The session variable implements session transmission. The following code can be used to describe it!
// Cookie disabled
1. php

The Code is as follows:

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

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.