So here's the scenario: I have user SIDs stored in database while active and I want to change/set a $_SESSION variable in the user's session. I do know there are other ways (Ajax, etc) to accomplish the same thing, but now I am intensely curious to see if there is a way to make this work.
Here's what I'm trying, User SessionID=1234567890 code, refreshed every 15 seconds:
if (isset($_SESSION['Message'])) {
$msg=$_SESSION['Message'];
$alert= "<br><script type='text/javascript'>alert('$msg');</script><br>";
unset($_SESSION['Message']);
} else {
$alert="<br>'Message' is NOT set.<br>";
}
And I run this on the server:
<?php
session_id('1234567890');
session_start();
$_SESSION['Message']="Hello!";
?>
And the result is the user session hangs on refresh instead of popping up the alert.
From the docs I have read, it seems like this is not specifically excluded, but I can see where it may cause slight security concerns. I have no security concerns in this case.
So, is there any way to make this work?
You are maybe running into an Issue called "Session blocking".
If a PHP-Script is running, it will lock it's current session-object on a file-system-level. Other PHP-Scripts calling start_session
for the very same ID will be stuck, until the first script has released the lock.
To avoid this, you can try to add session_write_close();
to your script(s), whenever you are sure, that the current script does not need to store any more data to the session-file.
Afterwards, you can still read the session during script execution but no longer write.
When you run PHP in CLI, it doesn't have session_path set. You'll need to execute the session_save_path() method and inform where your session files should be located.
For example:
bash# ls -al /var/www/tmp/sess_julp8r943vmbv18lhi651beu03
-rw------- 1 apache apache 19 Jun 20 21:09 /var/www/tmp/sess_julp8r943vmbv18lhi651beu03
bash# php -q
<?php
session_id ( "julp8r943vmbv18lhi651beu03");
session_start ();
var_dump ( $_SESSION);
?>
array(0) {
}
bash# php -q
<?php
session_save_path ( "/var/www/tmp");
session_id ( "julp8r943vmbv18lhi651beu03");
session_start ();
var_dump ( $_SESSION);
?>
array(1) {
["message"]=>
string(7) "Hello there!"
}