Question

I have always wondered, if a PHP session times out during the middle of executing a script, will the contents of the $_SESSION array still be available until script execution ends? For example:

session_start();

if(! isset($_SESSION['name'])) {
    echo 'Name is not set';
    exit;
}

// imagine there is a bunch of code here and that the session times out while
// this code is being executed

echo 'Name is ', $_SESSION['name']; // will this line throw an error?

Is it practical to copy session variables to the local scope so I can read them later on in the script without having to keep checking for a session time out? Something like:

session_start();

if(isset($_SESSION['name'])) {
    $name = $_SESSION['name'];
} else {
    echo 'Name is not set';
    exit;
}

// bunch of code here

echo 'Name is ', $name;
Was it helpful?

Solution

don't worry about such things. Nothing will happen to the session. It's initialised by sessioni_start() and $_SESSION will be always available within your script.

OTHER TIPS

The default three-hour session lifetime is reset each time you open the session (see session_cache_expire), so the only way a session could time out in the middle of a request is if a request takes three hours to process. By default PHP requests time out after just 30 seconds, so there's no danger of session expiry during a request. Furthermore, the $_SESSION variable won't suddenly change in the middle of a request. It's populated when the session starts, and that's it.

The variables are copied into the $_SESSION global at the initial request, so it has the same effect as copying it to a local variable.

However, for clarity sake, it makes sense to copy it to a local variable. Especially if you plan to use the variable several times. It can be difficult to read code that has $_SESSION['variable'] all over the place.

What you needed to understand is how sessions work. A client accessing a script using a $_SESSION super global only knows the key to the session that belongs to them (Stored in Cookie/URL). This means the session data itself has nothing to do with the client. If you have the key to the session data you want to use then you can use it. Older versions of PHP had some security holes because sessions where stored somewhere that was easily accessible (I don't remember details).

Basically, if you have the session id in a PHP script you have access to that session unless the memory on the machine is flushed/harddrive is corrupt (ie Computer Restart/Device Failure).

Hope this helps, otherwise go to php.net and dive into the details on how sessions work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top