How does session_start lock in PHP?

Posted by Morgan Cheng on Stack Overflow See other posts from Stack Overflow or by Morgan Cheng
Published on 2010-03-28T01:26:02Z Indexed on 2010/03/28 1:33 UTC
Read the original article Hit count: 374

Filed under:
|
|

Originally, I just want to verify that session_start locks on session. So, I create a PHP file as below. Basically, if the pageview is even, the page sleeps for 10 seconds; if the pageview is odd, it doesn't. And, session_start is used to obtain the page view in $_SESSION.

I tried to access the page in two tabs of one browser. It is not surprising that the first tab takes 10 seconds since I explicitly let it sleep. The second tab would not sleep, but it should be blocked by sessiont_start. That works as expected.

To my surprise, the output of the second page shows that session_start takes almost no time. Actually, the whole page seems takes no time to load. But, the page does take 10 seconds to show in browser.

obtained lock
Cost time: 0.00016689300537109
Start 1269739162.1997
End 1269739162.1998
allover time elpased : 0.00032305717468262
The page views: 101

Does PHP extract session_start out of PHP page and execute it before other PHP statements?

This is the code.

<?php

function float_time()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float)$sec + (float)$usec;
}

$allover_start_time = float_time();

$start_time = float_time();

session_start();

echo "obtained lock<br/>";
$end_time = float_time();

$elapsed_time = $end_time - $start_time;
echo "Cost time: $elapsed_time <br>";
echo "Start $start_time<br/>";
echo "End $end_time<br/>";
ob_flush();
flush();


if (isset($_SESSION['views']))
{
    $_SESSION['views'] += 1;
}
else
{
    $_SESSION['views'] = 0;
}

if ($_SESSION['views'] % 2 == 0)
{
    echo "sleep 10 seconds<br/>";
    sleep(10);
}

$allover_end_time = float_time();
echo "allover time elpased : " . ($allover_end_time - $allover_start_time) . "<br/>";

echo "The page views: " . $_SESSION['views'];

?>

© Stack Overflow or respective owner

Related posts about php

Related posts about session-start