Home > Backend Development > PHP Tutorial > Locks and concurrency of php session, phpsession_PHP tutorial

Locks and concurrency of php session, phpsession_PHP tutorial

WBOY
Release: 2016-07-12 09:00:11
Original
801 people have browsed it

PHP session locks and concurrency, phpsession

This article shares locks and concurrency issues during the use of PHP sessions. Related phenomena include request blocking and session data Lost, 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="/login/getCaptcha" id="img-captcha"/> 
Copy after login

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);
Copy after login

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 or 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 consumption of page display, and even cause request timeout and other unavailability. 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; 
Copy after login
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', '/');
}
Copy after login

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

Articles you may be interested in:

  • Multiple PHP servers to implement multiple sessions running concurrently
  • PHP method to solve session deadlock
  • Session variables in PHP Destruction
  • PHP error WARNING: SESSION_START() [FUNCTION.SESSION-START] Solution
  • Method of calling session data in ThinkPHP template
  • Achieving precise settings in php Methods for session expiration time
  • Detailed explanation of Session usage in ThinkPHP
  • Solution to blocking problems caused by PHP session file exclusive lock
  • Session in PHP may cause concurrency problems
  • A brief analysis of the concurrency problems that Session may cause in PHP

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1094746.htmlTechArticlephp session lock and concurrency, phpsession This article shares the lock and concurrency issues during the use of PHP session, Related phenomena include request blocking, session data loss, session data...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template