Home  >  Article  >  Backend Development  >  In-depth understanding of Session and Cookie in PHP_PHP Tutorial

In-depth understanding of Session and Cookie in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:04:12703browse

When setting a cookie on a page, you must refresh or go to the next page before you can use $_COOKIE to get the value of the variable.
The reason is because when the page is loaded by the browser for the first time, the cookie in the page will be Setting, send and store it to the storage location specified by the client, so $_COOKIE does not receive the value of the cookie variable sent by the client. When refreshing or going to the next page, the client will save it before the page program is run on the server. , send the cookie corresponding to the 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 be in the program. Send this cookie to the server before the server runs. (Personal opinion on this)
I am not very expressive, so sorry if I am unclear!

Set in php When using cookie arrays, you cannot use the method of adding data like in php:

Copy the code The code is as follows:

setcookie('my_cookie[]', 1);
setcookie('my_cookie[]', 2);
print_r($_COOKIE); // Array ( [my_cookie] => Array ( [0] => 1 ))
                                                                                                                                                                                                               // The value of the array has been added successfully, but the index has not changed, the subsequent data overwrites the previous data!
From this, we get
my_cookie[], which by default points to the position of the first element of the data, that is, the position with index
0. Note that it is different from that in php! Remember to specify the array element index when using cookie data in the future. !

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

Two methods to delete cookie variables:
1.php
Copy Code The code is as follows:

setcookie('user_name_1', 'zhaofei299', time()+3600); // The lifetime is 1 Hours
setcookie('user_name_2', 'ZHAOFEI299', time()+3600); // Lifetime is 1 hour
?>

2.php
Copy code The code is as follows:

setcookie('user_name_1'); >setcookie('user_name_2', "", time()-1); // The second type
print_r($_COOKIE); // Refresh the page more than 2 times and Array will be output ( [user_name_1] => )

/*Why is user_name_1 in the super global variable $_COOKIE not deleted (the fact that the variable is empty does not mean it does not exist), but
user_name_2 is deleted? That’s because the two ways of deleting variables are different!
The first one: sets the lifetime of the cookie, but sets its value to empty by default. The lifetime is the same as the browser. The cookie will be deleted only when the browser
is closed! So when Only when you reopen a browser and output the address will you find that all cookie variables have been deleted!
Comment out the two setcookie() functions in 2.php and take a look (the address is re-outputted)!
No. Two: The cookie lifetime is also set, which means that the cookie lifetime must expire and the cookie will be deleted. Therefore, when a new page is refreshed and the client sends the cookie to the server, $_COOKIE cannot get the cookie. The value of the cookie variable!
*/
?>


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


Copy code The code is as follows:
session_start();
print_r($_COOKIE);
?>


There are two ways to set cookies
header('set-cookie:user=zhaofei299');
setcookie('user', 'zhaofei299');
Session variables cannot be overloaded by GET data or POST data!
No need to serialize when using session variables to pass arrays and objects!
When using session variables to pass objects, when calling Before session_start(), the definition of the pair of class objects must be included, and the same is true for deserialization
(serialize)!
To delete a single session variable, you can use unset($_SESSION['***']) to delete it directly!
You cannot use unset($_SESSION) to delete all session variables, because this will delete all session information, including the PHPSESSID stored in COOKIE
, which destroys the session connection between the two pages. , you should use $_SESSION = array();
Eliminate the session id and lose contact between pages!
session_destroy();
Program Listing 1.1
Copy Code 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 again Look
$_SESSION['user'] = 'zhaofei299';
echo 'SESSION_ID: '.session_id().'
';
echo 'Test';
?>

Copy code The code is as follows:

session_start();
echo $_SESSION['user'];
echo session_id(); //The session variable has changed
?>

Two ways to pass session id (session_id):
1.cookie
2.url
Because the default session is based on cookies, and cookies are sent following the http protocol, so like cookies, there cannot be any output before
session_start()!
Now let’s mainly talk about the second type , pass the session id through the url
The SID constant has been defined in php to get the session id
sesssin_id use!
Copy the code The code is as follows :

session_start();
echo defined('SID')?'true':'false'; // true
echo SID; / / Nothing?
?>

Why is the value of SID null? Is there something wrong with it?
The reason is because the session is based on cookies by default, and SID will only be assigned when session_id passes data through url
!
Disable cookies in the browser, and you will find that SID has output instead of null!
Deleting session
requires three steps Step by step implementation.
Copy code The code is as follows:

session_destroy(); Step: Delete the server-side session file, use
setcookie(session_name(),'', time()-3600); // Step 2: Delete the actual session:
$_SESSION = array(); // Step 3: Delete the $_SESSION global variable array
?>

Everyone knows that session variables are saved on the server side, which means that session variables will be saved in a directory on the server. We
can find the session file in session.save_path in php.ini. Saved address.

The default session lifetime ends when browsing is closed, but you must know that after the session expires, when the page session_start() is opened, it will
determine whether the session id exists. If it does not exist, Just create one, otherwise the variable of the session id will be loaded into the page! Because the expired session_id will
be created a new one, but the session file it saved on the server side has not been deleted (close the browser, open the session file and save it
Take a look), so you need to use the session_destory() function to clear the session id and clear the corresponding session file at the same time. In this way, you can achieve the most
complete cleanup!

session_id uses url to pass the session When using variable data, because session_start() will determine whether the session id exists when opening the session. If it does not exist, create one. Otherwise, load the variable of the session id into the page!

And now it is used url to pass session_id, however, a session id will be generated every time you refresh/enter the page, so between pages, you cannot get the session_id variable set on another page, so there is no point in using session!



Solution:Before session_start(), manually set the session_id of the page, so that the page can get the session variable set in the previous page , thus realizing session transfer, as the following code can illustrate!//Disabled cookies
1.php


Copy code The code is as follows :
session_start();
$_SESSION['user'] = 'zhaofei299';
echo 'Next page';
?>


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

2.php


Copy code The code is as follows:
session_id($_GET[' PHPSESSID']); // Manually set session_id, you can use the
session_id variable of the previous page, and realize the session!
session_start();
print_r($_SESSION);
?>



Common session functions:
Copy code The code is as follows:
bool session_start(void); Initialize session
bool session_destroy(void): Delete the server-side session associated file.
string session_id() The id of the current session
string session_name() The name of the currently accessed session, which is the cookie name used by the client to save the session ID. The default is
PHPSESSID.
array session_get_cookie_params() The details of the session associated with this session.
string session_cache_limiter() Controls the client cache of pages using the session
ini session_cache_expire() Controls the client cache time
bool session_destroy () Delete the file that saves session information on the server side
void session_set_cookie_params ( int lifetime [, string path [, string domain [, bool
secure [, bool httponly]]]] ) Set the session associated with this session Details
bool session_set_save_handler (callback open, callback close, callback read, callback
write, callback destroy, callback gc) defines the function to handle the session, (not using the default method)
bool session_regenerate_id([bool delete_old_session]) allocate new session id



http://www.bkjia.com/PHPjc/327786.html

truehttp: //www.bkjia.com/PHPjc/327786.htmlTechArticleWhen setting a cookie on a page, you must refresh or go to the next page before you can use $_COOKIE to get the value of the variable .The reason is because when the page is loaded by the browser for the first time,...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn