


Dynamic web page technology PHP analysis of cookies and sessions_PHP tutorial
1. PHP COOKIE
Cookie is a mechanism that stores data on the remote browser side and uses it to track and identify users.
PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function.
1.1 Set cookies:
You can use the setcookie() or setrawcookie() function to set cookies. It can also be set by sending http headers directly to the client.
1.1.1 Use the setcookie() function to set cookies:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly]]]]] )
name: cookie variable name
value: cookie variable value
expire: end of validity period,
path: valid directory ,
domain: valid domain name, unique top-level domain
secure: If the value is 1, the cookie can only be valid on https connections, if it is the default value 0, both http and https are available.
Example:
$value = something from somewhere;
setcookie("TestCookie", $value); /* Simple cookie setting*/
setcookie("TestCookie", $value, time ()+3600); /* Valid for 1 hour*/
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); / * Valid directory/~rasmus, valid domain name example.com and all subdomains */
?>
Set multiple cookie variables: setcookie(var[a],value); use arrays to represent variables, But his subscript does not need quotation marks. In this way, you can use $_COOKIE['var']['a'] to read the COOKIE variable.
1.1.2. Use header() to set the cookie;
header( "Set-Cookie: name=$value[;path=$path[;domain=xxx.com[;...]]");
The following parameters are the same as those listed above for the setcookie function.
For example:
$value = something from somewhere;
header("Set-Cookie:name=$value");
1.2 Cookie reading:
Directly use php built-in super global variable $ _COOKIE can read the cookie on the browser side.
In the above example, the cookie "TestCookie" is set. Now let's read it:
print $_COOKIE[TestCookie];
Has COOKIE been output?!
1.3 To delete cookies
Just set the validity time to be less than the current time, and set the value to empty. For example:
setcookie("name","",time()-1);
Similar to using header().
1.4 FAQs:
1) There is an error message when using setcookie(). It may be because there is output or space before calling setcookie(). It may also be that your document is imported from other After the character set is converted, the document may have a BOM signature (that is, adding some hidden BOM characters to the file content). The solution is to prevent this situation from happening in your document. You can also use the ob_start() function. Handle it a bit.
2) $_COOKIE is affected by magic_quotes_gpc and may be automatically escaped
3) When using it, it is necessary to test whether the user supports cookies
2. PHP’s Session
session uses a cookie with an expiration time set to 0, and a unique identifier called session ID character (a long string of strings), some session files are synchronously generated on the server side (you can define the storage type of the session yourself), and are associated with the user machine. The web application stores data related to these sessions, and lets the data follow Users pass between pages.
Visitors to the website are assigned a unique identifier, a so-called session ID. It is either stored in a client-side cookie or passed via the URL.
Session support allows users to register any number of variables and reserve them for each request. When a visitor accesses the website, PHP checks whether a specific session ID was sent in the request, either automatically (if session.auto_start is set to 1) or when the user requests it (explicitly called by session_start() or implicitly by session_register()). If so, the previously saved environment is recreated.
2.1 Transmission of session ID
2.1.1 Transmission of session ID through cookie
Use session_start() to call the session. While generating the session file, the server generates the session ID hash value and the session with the default value of PHPSESSID. name, and sends the variable to the client (the default is) PHPSESSID (session name), the value is a 128-bit hash value. The server will interact with the client through this cookie.
The value of the session variable is PHP is internally serialized and stored in a text file on the server machine, and interacts with the client's coolie whose variable name is PHPSESSID by default.
That is, the server automatically sends the http header: header(Set-Cookie: session_name( )=session_id(); path=/);
That is, setcookie(session_name(),session_id());
When jumping to a new page from this page and calling session_start(), PHP will check and The session data stored on the server side associated with the given ID, if not found, creates a new data set.
2.1.2 Transmit session ID through URL
This is only used when the user prohibits the use of cookies. Method, because browser cookies are already universal, for security reasons, this method does not need to be used.
xxx, you can also pass the session value through POST.
2.2 Basic session usage example
// page1.php
session_start( );
echo Welcome to page #1;
/* Create session variable and assign value to session variable*/
$_SESSION[favcolor] = green;
$_SESSION[animal] = cat;
$_SESSION[time] = time();
// If the client uses cookies, you can directly pass the session to page2.php
echo
page 2;
// If the client disables cookies
echo
page 2 a>;
/*
By default under php5.2.1, the SID will only have a value when the cookie is written. If the cookie corresponding to the session
already exists, then the SID will be (undefined )Empty
*/
?>
// page2.php
session_start();
print $_SESSION[animal]; // Print out a single session
var_dump($_SESSION); // Print out the session value passed by page1.php
?>
2.3 Use the session function to control the page cache.
In many cases, we need to make sure we Whether the webpage is cached on the client, or the cache validity time needs to be set. For example, there are some sensitive contents on our webpage and you need to log in to view it. If it is cached locally, you can directly open the local cache and browse to the webpage without logging in. .
Use session_cache_limiter(private); you can control the page client cache, which must be called before session_start().
For more parameters, see http://blog.chinaunix.net/u/27731/showart.php ?Client cache control with id=258087.
To control the client cache time, use session_cache_expire(int); unit (s). It must also be called before session_start().
This is only to control the cache when using session Method, we can also control the cache of the control page in header().
2.4 Deleting session
requires three steps.
session_destroy(); : Delete the server-side session file, use
setcookie(session_name(),,time()-3600); // Step 2: Delete the actual session:
$_SESSION = array(); Three steps: Delete the $_SESSION global variable array
?>
2.5 Use of session in PHP large-scale web applications
For sites with a large number of visits, the default session storage method is not suitable. Currently The best way is to use the database to access the session. At this time, the function bool session_set_save_handler (callback open, callback close, callback read, callback write, callback destroy, callback gc) provides us with a solution to this problem.
The The six functions used by the function are as follows:
1. bool open() is used to open the session storage mechanism,
2. bool close() closes the session storage operation.
3. mixde read() from storage Use this function when loading session data
4. bool write() writes all data for the given session ID to storage
5. bool destroy() destroys the data associated with the specified session ID
6. bool gc() Garbage collection of data in the storage system
For an example, see the session_set_save_handler() function in the PHP manual.
If you use a class to process it, use
session_set_save_handler(
array(className,

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
