Home Backend Development PHP Tutorial PHP session control Cookie and Session

PHP session control Cookie and Session

Nov 14, 2017 pm 02:26 PM
cookie php session

PHP session control: Session and Cookie detailed explanation, session cookie

1. What is session control

HTTP is a stateless protocol. It does not have a built-in mechanism to maintain the state between two transactions. When a user requests one page and then requests another, HTTP has no way of telling us that both requests came from the same user.

The idea of ​​session control is to be able to track users according to a session in the website, so that it can easily support user login and display corresponding content according to their authorization level and personal preferences. We can This user behavior is recorded based on session control and a shopping cart can also be implemented.

2. Understand the basic session functions

PHP sessions are driven by a unique session ID, which is an encrypted random number. It is generated by PHP and will be saved on the client during the life cycle of the session. It can be saved in a cookie on the user's machine or passed on the network through the URL.

The session ID is like a key, which allows us to register some specific variables, which also become session variables. The contents of these variables will be saved on the server side. The session ID is the only information visible to the client. If the client can see the session ID through a cookie or URL during a specific website link, then we can access the session variables saved in the server for that session. By default, session variables are saved in ordinary files on the server.

Save the session ID in the URL. If there is a string of random numbers in the URL, it may be some form of session control.

Cookies are a different solution than sessions and also solve the problem of maintaining state across multiple transactions while also maintaining a clean URL.

Session control process: When a user logs in or browses a page of a site for the first time, the site will generate a PHP session ID and send it to the client (browser) through a cookie. When the user clicks on another page on the site, the browser begins connecting to this URL. Before connecting, the browser will first search for locally saved cookies, and if there are any cookies related to the URL being connected, it will be submitted to the server. Just when logging in or connecting for the first time, a cookie related to the URL of the website (saved session ID) has been generated, so when the user connects to the site again, the site can identify the user through this session ID. The session variable related to this session ID is taken out of the server's session file to maintain continuity between transactions.

3. What is Cookie

Cookie is created on the server side and written back to the client browser. The browser receives the instruction about writing the cookie in the response header and stores it in a local temporary file. Clamped. A cookie file is created, which stores your cookie content. The cookie content is stored in key-value pairs, and both the key and value can only be strings.

A cookie is actually a small piece of information that can be saved by a script on the client machine. A cookie can be set on the user machine by sending an HTTP header containing specific data in the following format:

Set-Cookie: NAME = VALUE; [expires=DATE;] [path=PATH; ] [domain=DOAMIN_NAME;] [secure]

This will create a cookie named NAME with a value of VALUE. Except for this parameter, all other parameters are optional. The expires field sets the expiration date of the cookie (if the expiration date is not set, it will be valid forever unless manually deleted). The path and domain fields are combined to formulate a URL or cookie-related URL. The secure keyword means that cookies are not activated in ordinary HTTP connections.

When the browser connects to a URL, it first searches for locally saved cookies. If there are any cookies associated with the URL being connected, the browser submits it to the server.


4. What is Session

Session is a server-side storage space maintained by the application server. When a user connects to the server, a unique session ID will be created and generated by the server. The session ID is used as an identifier to access the server-side Session storage space. During the session , the unique sessionID assigned to the client, used to identify the current user and distinguish it from other users. Accept each access request through SessionID to identify the current user, track and maintain the user's specific information, and session variables, which can store numeric or text information in the session. For example, session_name. This information is saved on the server side. Of course, the session ID can also be saved in the database as session information for session persistence. This can track the number of user logins, online or not, online time, etc., thereby maintaining the relationship between HTTP stateless things. The content storage of session is a list of key-value pairs, and the key is a string type. The storage of session is more convenient, and the value can be an object.

During the session, the session will be saved in two files on the client and server respectively. The client can save the sessionID in cookie mode (the default saving method) or pass it in the form of a url string. The server side is generally saved in the specified session directory in the form of text. On the server side, we can control which storage method the client uses through session.use_cookies. If it is defined as a cookie storage method, we can control the validity period of the cookie stored on the client through session.cookie_lifetime (default value 0, cleared when closing the browser). If the client uses a cookie to save the session ID, use a "temporary" cookie to save it (the name of the cookie is PHPSESSID. You can learn more about it through Firebug. You can change the name through php.ini session.name) , when the user submits the page, this SessionID will be submitted to the server to access the session data. This process does not require developer intervention.

5. Differences and connections between SESSION and COOKIE

The same point: both can solve the problem of HTTP statelessness, so that the same client can save data during multiple requests to visit the website. , set information, and establish connections between requested things.

Difference: Simply put, cookie information is stored on the client side, and session information is stored on the server side.

Session uses key-value pairs, which means that the ID is stored on the client side, and the value is placed on the server side. The user's ID is used to find the corresponding value on the server. In this way, the value is placed on the server side. There is a time limit, and the server will automatically recycle/release it when the time is up.

Cookies have two methods. One method is to save the value in the browser's variable and end when the browser is closed. The other method is to save it on the hard disk. As long as the time does not expire, the next Can still be used.

Contact: When the client uses the SessionID saved based on Cookie, the SessionID is generally saved in the cookie.

Note: Cookies are shared between browsers with the same core. Browsers with different cores are not shared, such as Firefox and IE (the storage locations are different, and of course they are not shared). Browsers with different kernels cannot share cookies and will also generate different sessionids.

The above is a detailed explanation of PHP session control. I hope it will be helpful to you.

Related recommendations:

PHP session control: Detailed explanation of Session and Cookie, sessioncookie

php session control, php session

Detailed introduction to the example code of php session control

php session control cookie and Session session processing_PHP tutorial

The above is the detailed content of PHP session control Cookie and Session. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles