Search code examples
phpsessionsession-storage

PHP session seen as local variable


I have a problem with PHP session. When i start session, and try to add a variable to it i can only get in the same PHP script where i declared it like it's normal variable. Browser debuger also seems to not see any variable in session.

<?php

echo session_start(); //This returns 1 so session is created
$_SESSION["A"] = "B"; 
echo $_SESSION["A"]; // And this prints "B" as predicted 

?>

But there is nothing in session!


Solution

  • You are confusing server-side PHP sessions, with the client-side JavaScript sessionStorage here. Both are two completely different things.

    https://www.php.net/manual/en/intro.session.php

    https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

    Browser debuger also seems to not see any variable in session.

    PHP session data is kept on the server, the browser can never “see it”, unless you explicitly output it somewhere (as you did with echo $_SESSION["A"];, but even then it of course won’t show in the sessionStorage debug panel.)


    i can only get in the same PHP script where i declared it like it's normal variable.

    Then you most likely neglected to pick your session up again in the other script files. You need to call session_start at the beginning of all of them.