I guess I am not understanding the scope of session variables, or the session itself, in PHP, hence this question:
This is my code
if(session_id()!=""){
echo "Getting rid of session"."</br>";
session_destroy();
}
echo "Before session_start(): ".isset($_SESSION["first_date_of_week"])."</br>";
session_start();
echo "After session_start(): ".isset($_SESSION["first_date_of_week"])." ".$_SESSION["first_date_of_week"]->format("Y-m-d")."</br>";
The output is:
Before session_start():
After session_start(): 1 2011-01-09
How come that when doing the isset(..) on the session variable it is set directly after starting the session, even though I haven’t even used it or set it yet? It does, however, still have the same value as before.
Also, session_id()=”” since the if-clause is never triggered. I never kill the session, how come it is set to “”? I.e. I refresh the page and expects the session to still be alive.
Using the isset(..) function is then pretty useless testing if it has been set already…
Thanks in advance!
/Niklas
There are a couple of problems with the code:
!session_id()==""is wrong because!has a higher precedence than==. It should be written assession_id() != "". Due to implicit conversions it should work correctly, but I can’t say it’s anything else than a bug.session_destroyonly works if called aftersession_start.Now, here’s what happens exactly:
session_destroyis never called (it would do nothing even if it were called).$_SESSION["first_date_of_week"]. Since there’s no active session,issetreturn false.$_SESSION["first_date_of_week"]now becomes available, but only because you had set it on some earlier session, in code that you don’t show.Try this code to get a better handle on what’s going on: