Home Backend Development PHP Tutorial Doubts about session in php

Doubts about session in php

Jul 25, 2016 am 09:07 AM

If you have any questions about session in php, please read this article carefully, I believe you will gain something.

For any doubts about session in php, please read this article carefully, I believe you will gain something.

1. PHP SESSION principle

We know that session is a method to maintain user session data on the server side, and the corresponding cookie is to maintain user data on the client side. The HTTP protocol is a stateless protocol. After the server responds, it loses contact with the browser. At the earliest, Netscape introduced cookies into the browser so that data can be exchanged across pages by the client. So how does the server remember the sessions of many users? What about data?

First of all, the client and server must be contacted one by one. Each client must have a unique identifier so that the server can identify it. It is recommended that there are two methods of unique identification: cookie or specified through GET. The default configuration of PHP will create a cookie named "PHPSESSID" when using a session (can be specified by modifying the session.name value in php.ini). If the client disables cookies, you can also specify to pass the session id to via GET. Server (modify parameters such as session.use_trans_sid in php.ini).

When we check the server-side session.save_path directory, we will find many files similar to sess_vv9lpgf0nmkurgvkba1vbvj915. This is actually the data corresponding to the session id "vv9lpgf0nmkurgvkba1vbvj915".

The truth is here. The server passes the session id to the server. The server finds the corresponding file based on the session id. When reading, it deserializes the file content to get the session value. When saving, it is serialized first and then written.

This is the fact, so if the server does not support session or you want to customize the session, you can DIY it. Use PHP's uniqid to generate a session id that will never be repeated, and then find a place to store the session content. You can also learn flickr Store the session in the mysql database.

2. Why must session_start() be executed before using session?

After understanding the principle, the so-called session is actually a session id on the client side and a session file on the server side. Executing session_start() before creating a new session tells the server to plant a cookie and prepare the session file. Otherwise, how will your session content be stored? ; Executing session_start() before reading the session tells the server to quickly deserialize the session file according to the session id.

Only one session function can be executed before session_start(). session_nam(): read or specify the session name (for example, the default is "PHPSESSID"). This of course must be executed before session_start.

3. Session affects system performance

Session does affect system performance on websites with high traffic volume. One of the reasons affecting performance is caused by the file system design. When there are more than 10,000 files in the same directory, file positioning will be very time-consuming. PHP supports session directory hashing. We can modify session.save_path = "2;/path/to/session/dir" in php.ini, then the session will be stored in a two-level subdirectory (revision: see david's reply), but it seems that PHP session does not support creation Directory, you need to create those directories in advance.

Another problem is the efficiency of small files. Generally, our session data is not too large (1~2K). If there are a large number of 1~2K files on the disk, the IO efficiency will definitely be very poor. PHP Manual It is recommended to use the Reiserfs file system, but the future of Reiserfs is worrying. The author of Reiserfs killed his wife, and SuSE also abandoned Reiserfs.

In fact, there are many ways to store sessions, which can be viewed through php -i|grep "Registered save handlers". For example, Registered save handlers => files user sqlite eaccelerator can be saved through files, users, sqlite, and eaccelerator. If the server is installed With memcached, there is also the option of mmcache. Of course there are many more, such as MySQL, PostgreSQL, etc. All are good choices.

4. Session synchronization

We may have many servers on the front end. The user logs in on server A, plants the session information, and then visits some pages of the website and may jump to server B. If there is no session information on server B at this time and no action is taken, Special handling may cause problems.

There are many types of session synchronization. If you store it in memcached or MySQL, it is very easy. Just specify it to the same location. If it is in file form, you can use NFS to store it uniformly.

Another way is to use encrypted cookies. The user logs in successfully on server A and plants an encrypted cookie on the user's browser. When the user visits server B, check whether there is a session. If there is, of course there is no session. Question, if not, check whether the cookie is valid. If the cookie is valid, re-establish the session on server B. This method is actually very useful. It is very useful if the website has many sub-channels and the servers are not in the same computer room. The sessions cannot be synchronized and you want to log in uniformly.

Of course, another method is to maintain the session at the load balancing layer, and assign the visitor to a certain server. All his visits will be on that server, so there is no need for session synchronization. These are all at the operation and maintenance level. thing.

That’s all, choose to use session according to your own application. Don’t be timid just because everyone says that session affects system performance. Knowing the problem and solving it are the key. If you can’t afford to offend or hide, you are not suitable here.



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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles