Php session read/write lock
Let's take a look at an example. function:
1. Click a button on the page, ajax executes php, and php uses session to record the step to be executed.
2. Use ajax to poll another php to obtain the data in the session and output the execution step.
Session.htmlCall php to execute and output the execution to the first step
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
Handle. phpExecute and record the execution to the first step
<?phpsession_start();$_SESSION['step'] = '';$n = 1;while($n<=10){ $_SESSION['step'] = $n; sleep(1); $n++;}$_SESSION['step'] = 'complete';?>
Getstep. phpObtain the steps to execute
<?phpsession_start();echo isset($_SESSION['step'])? $_SESSION['step'] : '';?>
During execution, it is found that not every step is returned, but the complete is returned 10 seconds later.
When session_start () is executed, the session is locked. Until the page is executed.
Therefore, during the execution of the page, write operations on the sesssion will only be saved in the memory and will not be written into the session file.
To read a session, you need to wait until the session lock is unlocked.
We can use session_write_close () to write data to the session file and end the session process. In this way, you do not need to wait for the page to be executed to complete, and you can also obtain the step to be executed.
But there is a problem, that is, after executing sesssion_write_close (), any write operation on the session will not work. Because the session process has ended.
Therefore, when you need to write a session, add session_start ()
Session_start-Start new or resume existing session
Session_write_close-Write session data and end session
Handle. phpFollow these steps to obtain the execution step.
<? Phpsession_start (); $ _ SESSION ['step'] = ''; $ n = 1; while ($ n <= 10) {$ _ SESSION ['step'] = $ n; session_write_close (); // write data to the session file and end the session process session_start (); // re-create the session process sleep (1); $ n ++;} $ _ SESSION ['step'] = 'complete';?>