search
HomeBackend DevelopmentPHP TutorialPHP session locks and concurrency_php tips

This article shares locking and concurrency issues during the use of PHP sessions. Related phenomena include request blocking, session data loss, and session data cannot be read.

I can’t log in
One day, I was going to log in to one of our backend systems to solve a bug. Even though I entered the account and password verification codes accurately, I couldn't log in. After many experiments, I found that there were two main error messages:

  • csrf verification failed
  • The verification code is wrong [I swear to the code gods that I entered the verification code I saw using half-width, and the order was consistent, without extra characters]

Our System
Our system is developed based on phalcon 2.0.8. As you can see, we have added fields to prevent CSRF attacks in the form fields. Captcha is also enabled.

<input type="hidden" 
  name="{{ security.getTokenKey() }}"
  value="{{ security.getToken() }}"/>
<img  src="/static/imghwm/default1.png"  data-src="/login/getCaptcha"  class="lazy" id="img-captcha"/ alt="PHP session locks and concurrency_php tips" > 

I first checked these two components and found that they both store data in the session:

# phalcon/security.zep
# Security::getToken()
let session = <SessionInterface> dependencyInjector->getShared("session"); 
session->set(this->_tokenValueSessionID, token); 
$this->session->set('admin_get_captcha_action', $captcha);

Then I checked the implementation of our session and found that the data is stored in redis.

Looking and looking
What is the problem that prevents me from logging in? Since there is a problem with data verification, let’s start with the data. I logged in to the redis machine in our test environment, executed redis-cli monitor, and then went through the login process and found the output as follows (meaning):

  • GET sessionId
  • GET sessionId
  • SETEX sessionId 3600 csrf=xxxx
  • SETEX sessionId 3600 captcha=abcd

We can see:

1. There are two requests here, one is to load the form, and the other is to generate the verification code.
2. There is a "concurrency" situation. These two requests should request the verification code after the form is loaded and rendered. That is, the session sequence should be get->set->get->set. Why does it seem to be concurrent? Requested.
3. The latter SETEX has no csrf content, which means it overwrites the previous data
The whole world is not good, but I understand a little bit what the problem is. What's the problem? It's a long story, starting with PHP's session data access.

Access to php session data
The session data is encoded into a string and stored in the storage [file, db, redis, memcache, etc.]. When we use the session, when do we get the data from the storage? When is the data written to memory?

The answer to this question may be different from what some friends think. In a request, PHP will only read the memory once, during session_start, and then it will only write to the memory once, at the end of the request, or by calling During session_write_close, the data is flushed back to the memory and the session is closed.

Then the question is:

1. If there are two read and write session requests in a session at the same time, there is no guarantee of getting 1-writing 1-getting 2-writing 2, and there is no cas version management mechanism, these concurrent requests will interact with each other. If the other party's write cannot be read, the last write will overwrite the session written by the previous request.
2. If the request is serial, such as the form and verification code on the login page, it is possible that the previous request has already output the content, but the session has not yet been written, and the subsequent request has been initiated.
Locked and Unlocked
Solving the concurrency of such resources is generally handled through locks or version management. But I don't see a good way to do version management. Let’s talk about locks.

In fact, locks are not very suitable and have disadvantages.

PHP sessions are stored in files by default. When the session is opened, an exclusive lock will be added to the file. In this way, other requests cannot obtain the lock and can only wait until the previous lock is released.

This ensures the order of read-write, read-write.

Other storage, such as mysql, can use select for update to perform row locks. Redis can be implemented through an auto-increment key, returning 1 to acquire the lock, etc.

This implementation is ideal for data flow. However, for the current situation where ajax is widely used on pages, all requests will be queued for processing, which will greatly increase the time it takes to display the page, and may even cause unavailability such as request timeout. Fault.

There is no solution
It is not recommended to use session too much. The problems caused by its read-once-write-once mechanism will cause pitfalls.
Call session_write_close
before template rendering or output request

# 立刻回写session,避免session覆盖
$eventManager = $this->view->getEventsManager();
if (!$eventManager) { 
  $eventManager = new Manager();
  $this->view->setEventsManager($eventManager);
}
$eventManager->attach("view:afterRender",function(){
  session_write_close();
});
return $this->view; 
if($login) { 
  # 立刻回写session,避免session读取不到
  $eventManager = $this->dispatcher->getEventsManager();
  if (!$eventManager) {
    $eventManager = new Manager();
    $this->dispatcher->setEventsManager($eventManager);
  }
  $eventManager->attach('dispatch:afterDispatchLoop',function(){
    session_write_close();
  });
  return $this->response->setHeader('Location', '/');
}

The above is about the locking and concurrency of php session. I hope it will be helpful to everyone's learning.

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version