John Smith
John Smith

Reputation: 6201

Php, share SESSION between requests, forcing session_id

My goal is to share session between requests, I meant every request could reach a data. First I was thinking that simply sharing via filesystem could be good, but I find out this by myself:

session_id('0');
session_start();
echo session_id();
var_dump ($_SESSION);
if (!isset($_SESSION['x']))
{
    $_SESSION['x'] = 0;
}
$_SESSION['x']++;
var_dump ($_SESSION);

this way I can see the same from browsers. My question is, is it a good practice?

EDIT: here is the full working version:

$m = microtime(true);
session_start();
if (session_id() == '0') // this happens when somehow our session id sticks, it should not happen ever, but if so, lets erase it
{
    setcookie (session_name(), '', time() - 3600);
    session_destroy();
    session_write_close();
    echo 'reload'; die;
}
if (!isset($_SESSION['x']))
{
    $_SESSION['x'] = 0;
}
$_SESSION['x']++;
$saveId = session_id();
session_write_close();

// switch to common storage
session_id('0');
session_start();
if (!isset($_SESSION['common']))
{
    $_SESSION['common'] = 0;
}
$_SESSION['common']++;
session_write_close();

// back to our own session
session_id($saveId);
session_start();

echo $_SESSION['x'].'<br>'.(microtime(true) - $m); die;

I dont thing its very time consuming.

Upvotes: 1

Views: 323

Answers (1)

Rob Baillie
Rob Baillie

Reputation: 3470

It's tricky to know if SESSION is the right place to put this data, but it's worthwhile bearing some things in mind.

  • SESSION is designed to store data related to an individual user's visit to your site (normally being distinguished the combination of machine and browser, thanks to the session id being stored in a client side cookie).
  • Default behaviour of the PHP session handler is to:
    • Store the data in a file on the server.
    • Block concurrent access to that file.
  • It is possible to have multiple sessions for a given request, but that means ensuring you start and end each session and ensure that you keep track of the session IDs - I'm not entirely sure how you would do this without manually writing data into the client's cookie.

All in all you'll probably find that your performance using the session will be slower that just checking the existence of the file anyway (which is simpler than using the session, in terms of work done by PHP).

That said, if you're writing to that file then you're just going to have concurrency issues that you'll have to solve in much the same way as php sessions do anyway.

I'd say, if you're writing data, then look to your DB. It's what they're designed for.

If you don't want to write to your primary DB and have good reason for that, then maybe consider something like a memcache DB, or some other secondary storage.

Upvotes: 1

Related Questions