PHP session lock, concurrency, overlay detailed

Source: Internet
Author: User
Tags php session
This article mainly and everyone introduced the PHP session lock and concurrency, and related to the phenomenon of request blocking, session data loss, session data can not read the problem, interested in small partners to refer to, hope to help everyone.

I can't log in.
One day, I am going to log on to our back-end system, to solve a bug, in the account password verification code is accurately entered in the case, I am not logged on, after many experiments found that there are two main error messages:

    • CSRF Validation Failure

    • CAPTCHA error "I swear to God I used half-width to enter the verification code I see, and in the same order, no extra characters"

Our system is developed based on Phalcon 2.0.8, as you can see, we have added a domain to prevent CSRF attacks in the form field. The verification code is also enabled.

<input type= "hidden"   name= "{{Security.gettokenkey ()}}"  value= "{{Security.gettoken ()}}"/>

I first looked at the two components and found that they were all keeping the data in 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 looked at the implementation of our session and found that it was storing the data in Redis.

looking for what problems caused me not to log on? Since there is a problem with data validation, start with the data, I landed in our test environment of the Redis machine, 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, one is the form load, one is to generate a verification code.
2, there is "concurrency" situation, these two requests should be the form load rendering before requesting the verification code, that is, the session sequence should be get->set->get->set, it seems to be a concurrent request.
3, the back of the Setex no CSRF content, that is, to cover the previous data
The whole world is not good, but also slightly understand what is the problem. What's the problem, it's a long story, to start with the access to the session data from PHP.

PHP Session data Access session data is encoded into a string stored in the memory "file, DB, Redis, memcache and so on", when we use the session, when we go to the memory to fetch data? When did the data be written to the memory?

The answer to this question may not be the same as some friends think, in a request, PHP will only read the memory once, in Session_Start, and then only write once memory, at the end of the request, or call Session_write_close, Swipe the data back into memory to close the session.

So here's the question:

1, if a session, at the same time, there are two read and write session requests, there is no guarantee to get 1-write 1-Get 2-write 2, without the CAS version management mechanism, these concurrent requests will not be read to each other's write, the last write will overwrite the previous request to write the session.
2, if the request is serial, like the login page of the form and verification code, it is possible that the previous request has been output, but the session has not been written, the subsequent request has been initiated.
Lock and no lock
Concurrency that resolves this resource is typically handled through lock or versioning. But version management I don't see a good way. Let's talk about locks.

In fact, the lock is not suitable, there are drawbacks.

PHP session, the default is the file storage, in the open session, the file will be exclusive lock, so that the other requests can not acquire the lock, only wait until the previous lock solution.

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

Other memory, such as MySQL, can be row locked with select for update. Redis can be implemented by a self-increment key, which returns 1 of the acquisition to the lock.

This implementation, the data flow is ideal, but for the current situation of such a large number of AJAX applications, all requests queued processing, will greatly increase the time of the page display, and even the request timeout and other unavailable failures.

Unresolved resolution does not recommend excessive use of the session, its one-time read write mechanism caused by the problem, will cause the existence of pits.
Call Session_write_close before the template is rendered or before the output is requested

# immediately write back to the session to avoid session overwrite $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) {   # immediately write back to the session to avoid the 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 ', '/');}

Related recommendations:

Instance analysis of blocking request in PHP session lock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.