In-depth understanding of Session and Cookie in PHP

Source: Internet
Author: User
Tags set cookie

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:
Copy codeThe Code is as follows: <? Php
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. phpCopy codeThe Code is as follows: <? Php
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. phpCopy codeThe Code is as follows: <? Php
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!Copy codeThe Code is as follows: <? Php
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, including stored in cookies.
PHPSESSID in, that is, the SESSION connection between the two pages is broken. use $ _ SESSION = array ();
Eliminates session IDs and disconnects pages!
Session_destroy ();
Procedure 1.1Copy codeThe Code is as follows: <? Php
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 ().' <br/> ';
Echo '<a href = "3.php" target =" _ blank "> test </a> ';
?>

Copy codeThe Code is as follows: <? Php
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!Copy codeThe Code is as follows: <? Php
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 output, instead of null!
Delete session
Three steps are required.Copy codeThe Code is as follows: <? Php
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 to obtain
The session variable implements session transmission. The following code can be used to describe it!
// Cookie disabled
1. phpCopy codeThe Code is as follows: <? Php
Session_start ();
$ _ SESSION ['user'] = 'zhaofei299 ';
Echo '<a href = "2.php? '. SID.' "> next page </a> ';
?>

1. The 4th line of php code can also be written as echo '<a href = "2.php"> next page </a> ';
You can set session. use_trans_sid in php. ini to 1, so that when the session id is passed using the url,
The browser automatically appends session_id to the end of the url!
Just like entering www.baidu.com in a browser, the browser will automatically replace it with a http://www.baidu.com/

2. phpCopy codeThe Code is as follows: <? Php
Session_id ($ _ GET ['phpsessid ']); // manually set session_id.
The session_id variable implements the session!
Session_start ();
Print_r ($ _ SESSION );
?>

Common session functions:
Copy codeThe Code is as follows: bool session_start (void); initialize the session
Bool session_destroy (void): deletes the session associated files on the server.
String session_id () id of the current session
String session_name () indicates the name of the session currently accessed, that is, the cookie name used by the client to save the session ID. The default value is
PHPSESSID.
Array session_get_cookie_params () details of the session associated with this session.
String session_cache_limiter () controls the client cache of pages using sessions
Ini session_cache_expire () controls the Client Cache Time
Bool session_destroy () deletes the file on the server that stores session information.
Void session_set_cookie_params (int lifetime [, string path [, string domain [, bool
Secure [, bool httponly]) sets the session details associated with this session
Bool session_set_save_handler (callback open, callback close, callback read, callback
Write, callback destroy, callback gc) defines the function for processing the session (not by default)
Bool session_regenerate_id ([bool delete_old_session]) allocates a new session id

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.