Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sessions - Locking and Sharing questions

Tags:

php

session

I would like to know if it is possible to read $_SESSION attributes without locking it.
Currently, session_start() locks SESSION, that means other PHP processes will wait until it is unlocked.
But, some processes just want to get some $_SESSION variables, not to write on them.
Is that possible to implement some function like session_get(string $id) which doesn't lock SESSION?

Also, it is possible to share SESSIONs between browsers, once the user is logged in the same account, for example, using session_id('shared_vars_of_'.$userid). But, is that secure? Is this discouraged?

Thanks,
Nuno

like image 314
Nuno Avatar asked Dec 29 '22 15:12

Nuno


2 Answers

Personally I do this right at the start:

session_start();
session_write_close();

And then you have access to $_SESSION as read-only. As you can see below, you do not need to copy the session variables.

session_start();
//This value will be "The #1 Value!" only the 2nd time you run this
echo "<br />myData value1:".$_SESSION['myData'];
$_SESSION['myData'] = "Value 2 and 3!";
session_write_close();

echo "<br />myData value2 (read-only):".$_SESSION['myData'];
$_SESSION['myData'] = "Value 3 Misleading, and never actually written to the session!";
//But it will affect this value, obviously
echo "<br />myData value3:".$_SESSION['myData'];

session_start();
//NOTE HOW THE ABOVE LINE WRITES-OVER $_SESSION
echo "<br />myData value4:".$_SESSION['myData'];
$_SESSION['myData'] = "The #1 Value!";
session_write_close();
like image 55
Snap Avatar answered Jan 09 '23 21:01

Snap


Interesting question!

session_write_close() is not exactly what you're asking for but it should help speed up the process:

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.

A script that needs only read-only access could start the session, copy the session variables into another array and apply session_write_close(). It won't be a fully read-only solution - it could be that you'd need to build your own session handler for that - but it should be a big step forward.

Update: I just found an interesting issue from 2001 in the PHP 4 tracker that seems to introduce a patch enabling read only sessions - it doesn't seem to have made it to the official releases, though, at least not according to the documentation! Maybe it's worth digging further or reopening the Ticket for PHP 5.

like image 42
Pekka Avatar answered Jan 09 '23 20:01

Pekka