


In-depth understanding of Session and Cookie in PHP_PHP Tutorial
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:
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
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
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!
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
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';
?>
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!
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.
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
$_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
session_id variable of the previous page, and realize the session!
session_start();
print_r($_SESSION);
?>
Common session functions:
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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
