search
HomeBackend DevelopmentPHP TutorialThe working principle and usage of session_PHP tutorial

Session working principle and session usage

Let’s look at a session instance first

function getsessiondata ($session_name = ' sessid', $session_save_handler = 'files') {
     $session_data = array();
     # did we get told what the old session id was? we can't continue it without that info
     if (array_key_exists($session_name, $_cookie)) {
         # save current session id
         $session_id = $_cookie[$session_name];
         $old_session_id = session_id();
        
         # write and close current session
         session_write_close();
        
         # grab old save handler, and switch to files
         $old_session_save_handler = ini_get('session.save_handler');
         ini_set('session.save_handler', $session_save_handler);
        
         # now we can switch the session over, capturing the old session name
         $old_session_name = session_name($session_name);
         session_id($session_id);
         session_start();
        
         # get the desired session data
         $session_data = $_session;
        
         # close this session, switch back to the original handler, then restart the old session
         session_write_close();
         ini_set('session.save_handler', $old_session_save_handler);
         session_name($old_session_name);
         session_id($old_session_id);
         session_start();
     }
    
     # now return the data we just retrieved
     return $session_data;
 }

Look at the session principle again
I have been using sessions to store data, but I have never summarized the use of sessions and their working principles. Today I will summarize them here.
The introduction here is mainly based on the PHP language. The operations in other languages ​​may be different, but the basic principles remain the same.

1. How to operate session in php:
session_start(); //Use this function to open the session function
$_session ​ //Use predefined global variables to manipulate data
Use unset($_session['key']) //Destroy the value of a session
It's simple to operate, everything is done by the server; since the processing is in the background, everything also looks safe. But what mechanism does session use, how is it implemented, and how is the session state maintained?

2.session implementation and working principle
The browser and server use http stateless communication. In order to maintain the state of the client, session is used to achieve this purpose. But how does the server identify different clients or users?
Here we can use an example from life. If you attend a party and meet many people, how will you distinguish different people? You may base it on the face shape or the user’s name
Or a person's ID card, which uses a unique identification. In the session mechanism, such a unique session_id is also used to identify different users. The difference is: the browser will bring
with every request. The session_id generated for it by the server.
Let’s briefly introduce the process: when the client accesses the server, the server sets the session according to the needs, saves the session information on the server, and passes the session_id indicating the session to the client browser,
The browser saves this session_id in memory (there are other storage methods, such as writing it in the URL), which we call a cookie without expiration time. After the browser is closed, this cookie will be cleared, and it will not contain the user's temporary cookie file.
In the future, the browser will add this parameter value to every request, and the server can obtain the client's data status based on this session_id.
If the client browser is closed unexpectedly, the session data saved by the server is not released immediately. The data will still exist at this time. As long as we know the session_id, we can continue to obtain the session information through requests; but at this time, the background session still exists. But the session save has an expiration
time, once there is no client request for more than the specified time, he will clear the session.
The following introduces the session storage mechanism. The default session is saved in files, that is, session data is saved in the form of files. In php, it is mainly based on the configuration of php.ini session.save_handler
to choose how to save the session.
By the way, if we want to use LVS of the server, that is, multiple servers, we generally use memcached session, otherwise some requests will not be able to find the session.
A simple memcache configuration:
session.save_handler = memcache
session.save_path = "tcp://10.28.41.84:10001"
Of course, if we must use files file caching, we can use nfs to store all session files in one place.
As mentioned just now, the session-id returned to the user is eventually saved in memory. Here we can also set parameters to save it in the user's URL.

3. Example problem
Existing systems a and b; Assume that system a is a web system that can run independently, that is, it can handle sessions directly with the browser. System b is based on mobile and needs to call the functional interface of system a.
While a remains unchanged, that is, login verification and session storage remain unchanged, system b can handle the front-end user's request.
The solution provided here is implemented using php
After the user successfully logs in, the session-id of the saved session is returned to system B, and then system B carries the session_id every time it requests other interfaces.
ASystem A adds session_id (session_id) before session_start;
In this way, system b can safely call a


The session function also has

session_cache_expire — return current cache expire
session_cache_limiter — get and/or set the current cache limiter
session_commit — alias of session_write_close
session_decode — decodes session data from a string
session_destroy — destroys all data registered to a session
session_encode — encodes the current session data as a string
session_get_cookie_params — get the session cookie parameters
session_id — get and/or set the current session id
session_is_registered — find out whether a global variable is registered in a session
session_module_name — get and/or set the current session module
session_name — get and/or set the current session name
session_regenerate_id — update the current session id with a newly generated one
session_register — register one or more global variables with the current session
session_save_path — get and/or set the current session save path
session_set_cookie_params — set the session cookie parameters
session_set_save_handler — sets user-level session storage functions
session_start — initialize session data
session_unregister — unregister a global variable from the current session
session_unset — free all session variables
session_write_close — write session data and end session


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/447021.htmlTechArticlesession 的工作原理与session用法 先来看一个session实例 function getsessiondata ($session_name = sessid, $session_save_handler = files) { $session_data = array(); # di...
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
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft