Deep understanding of the session and cookie_php techniques in PHP

Source: Internet
Author: User
Tags session id sessions setcookie
When you set up a COOKIE on a page, you must refresh or go to the next page to get the value of the variable with $_cookie.
The reason is because when the page is first accessed by the browser, the cookie in the page is set up and sent to the storage location specified by the client, so $_cookie does not receive the value of the cookie variable sent by the client, and when it refreshes or to the next page, The client sends a COOKIE corresponding to the address to the server before the page program runs on the server side, so $_cookie can get the value! To be honest, when each page is accessed, if the client finds a cookie that corresponds to the access address, it sends the cookie to the server before the program runs on the server side. (personal view of this)
my ability to express is not strong, if there is unknown, but also please sorry!

When you set up a cookie array in PHP, you can't use the same method as in PHP to add data:
Copy Code code as follows:

<?php
Setcookie (' my_cookie[] ', 1);
Setcookie (' my_cookie[] ', 2);
Print_r ($_cookie); Array ([My_cookie] => Array ([0] => 1))
The value of the array is added successfully, but the index does not change, and the data behind it overwrites the previous data!
From this
My_cookie[], the default point to the position of the first element of the data, that is, the index is
0 of the location. Note that it's not the same as in PHP! Remember to specify an array element index later with cookie data Oh!

$my _cookie[] = 1;
$my _cookie[] = 2;
Print_r ($my _cookie); Array ([0] => 1 [1] => 2)
?>

two ways to delete a cookie variable:
1.php
Copy Code code as follows:

<?php
Setcookie (' user_name_1 ', ' zhaofei299 ', Time () +3600); Lifetime of 1 hours
Setcookie (' user_name_2 ', ' ZHAOFEI299 ', Time () +3600); Lifetime of 1 hours
?>

2.php
Copy Code code as follows:

<?php
Setcookie (' user_name_1 '); First Kind
Setcookie (' user_name_2 ', "", Time ()-1); Second Kind
Print_r ($_cookie); Refresh page 2 above will output Array ([user_name_1] =>)

* * Why the User_name_1 in the Super global variable $_cookie is not deleted (the variable is empty does not mean not exist), and
User_name_2 was deleted? That's because two different ways to delete a variable!
The first: The lifetime of the cookie is set, except that its value is set to NULL by default, and the lifetime is the same as the browser, the browser
The cookie is removed when it is turned off! So when you reopen a browser, you will find that the cookie variable is all deleted!
Comment out the two Setcookie () function sections in 2.php (re-output the address)!
The second: Also set the lifetime of the cookie, is to make the lifetime of the cookie must expire, the cookie is deleted, so brush
New page, when the client sends a cookie to the server, $_cookie does not get the value of the cookie variable!
*/
?>

The session ID is stored in the client cookie by default!
Copy Code code as follows:

<?php
Session_Start ();
Print_r ($_cookie);
?>

There are two ways to set up cookies
header (' set-cookie:user=zhaofei299 ');
Setcookie (' user ', ' zhaofei299 ');
Session variables cannot be overloaded by get data or post data!
Using the session variable to pass the array, the object does not need to be serialized!
When you pass an object with a session variable, you must include the definition of the class object before calling Session_Start (), and deserialize the
(serialize) is also true!
Deleting a single session variable can be deleted directly using unset ($_session[' * * *])!
Deleting all session variables can not be done with unset ($_session), as this will remove all session information, including stored in cookie
PHPSESSID, which is to destroy the conversation between two pages, should use $_session = Array ();
Eliminates the session ID and causes the page to lose contact!
Session_destroy ();
Program Listing 1.1
Copy Code code as follows:

<?php
Session_Start ();
Header (' Content-type:text/html;charset=utf-8 ');
$_session[' a '] = ' a ';
$_session[' b '] = ' B ';
Unset ($_session); After the test, then note the next look
$_session[' user ' = ' zhaofei299 ';
Echo ' session_id: '. session_id (). ' <br/> ';
Echo ' <a href= "3.php" target= "_blank" > Test under </a> ';
?>

Copy Code code as follows:

<?php
Session_Start ();
echo $_session[' user '];
Echo session_id (); The session variable changed
?>

The session ID (SESSION_ID) is passed in two ways:
1.cookie
2.url
Because the default session is based on cookies, and cookies are sent following the HTTP protocol, the same as cookies,
Session_Start () can not have any output before!
Now basically say the second one, pass the session ID through the URL
PHP has defined the SID this constant to get the session ID
The use of sesssin_id!
Copy Code code as follows:

<?php
Session_Start ();
echo defined (' SID ')? True ': ' false '; True
Echo SID; There's nothing?
?>

Why would the value of a SID be null? What's wrong with it?
The reason is that the session defaults to cookies, and the SID only session_id through the URL
The value is assigned when the data is passed!
When you disable cookies in the browser, you will find that the SID has an output, not a null!
Delete session
Be implemented in three steps.
Copy Code code as follows:

<?php
Session_destroy (); The first step: Delete the server-side session file, which uses
Setcookie (Session_name (), ", Time ()-3600); Step two: Delete the actual session:
$_session = Array (); Step three: Delete the $_session global variable array
?>

We all know that the session variable is saved on the server side, which means that the variables of the sessions are saved in a directory in the server, and I
You can find the address saved in the session file in the Session.save_path in php.ini.

The default session lifetime is the end of the browse shutdown, but you should know that after the end of the conversation expiration, when the page session_start ()
To determine if a session ID exists, create one if it does not exist, or load the variable of the session ID into the page! Because expired session_id will
was created a new, but it was saved on the server side of the session file and was not deleted (closes the browser, opens the session file to save
, so you want to use the Session_destory () function to clear the session ID, and also clear the corresponding session file, so you can do the most
Thorough clearance!

session_id uses a URL to pass session variable data because Session_Start () determines whether the session ID is saved when the conversation is opened
In, create one if it does not exist, otherwise load the session ID's variable into the page!

Instead of using a URL to pass session_id, each refresh/Enter page will generate a session ID, so the page is
You can't get a session_id variable that was set on another page, then it doesn't make sense to use the session!

Workaround:Before Session_Start (), manually set the session_id of the page so that the page can be set on the previous page
Session variable, also realize the conversation of the transfer, the following code can be explained!
Cookies are disabled
1.php
Copy Code code as follows:

<?php
Session_Start ();
$_session[' user ' = ' zhaofei299 ';
Echo ' <a href= ' 2.php '. SID. ' " > next page </a> ';
?>

The 4th line of 1.php code can also be written as: Echo ' <a href= "2.php" > next page </a>;
You can set the Session.use_trans_sid in php.ini to 1 so that when the session ID is passed by using a URL,
The browser will automatically append the session_id to the back of the URL!
As if you were typing in a browser: www.baidu.com, the browser will automatically replace it with http://www.baidu.com/

2.php
Copy Code code as follows:

<?php
session_id ($_get[' phpsessid ')); Manually set session_id, this can be used on the previous page
session_id variable, also realize the session!
Session_Start ();
Print_r ($_session);
?>

Common session functions:
Copy Code code as follows:

BOOL Session_Start (void); Initializing session
BOOL Session_destroy (void): Deletes a server-side session Association file.
String session_id () ID of the current session
String Session_name () The session name that is currently accessed, that is, the cookie name where the client holds the session ID. Default
Phpsessid.
Array Session_get_cookie_params () the details of the session associated with this session.
String Session_cache_limiter () controls client-side caching of pages that use session
INI session_cache_expire () control client cache time
BOOL Session_destroy () Deletes a file that holds session information on the server side
void session_set_cookie_params (int lifetime [, String path [, string domain [, bool
secure [, BOOL HttpOnly]]]] Set the details of the session associated with this session
BOOL Session_set_save_handler (callback open, callback close, callback read, callback
Write, callback destroy, callback GC) defines functions that process sessions (not by default)
BOOL SESSION_REGENERATE_ID ([bool delete_old_session]) assigns 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.