search
HomeBackend DevelopmentPHP TutorialPHP session control Cookie and Session

PHP session control Cookie and Session

Nov 14, 2017 pm 02:26 PM
cookiephpsession

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.