I've been coding a website for a long time, but never used the session_name()
function built in PHP to set a custom session name instead of the default (PHPSESSID).
I've had a login page that redirects you to another file after a successful login. In that file, I was basically checking isset($_SESSION)
if I wasn't set I redirect to the login page. Otherwise, I say Hello $_SESSION["Username"]
.
I've recently decided to use the session_name
and set a custom name. However, now the script in the second file (checking if $_SESSION
was set) always says it's not set. I just changed the session name.
Then I searched around on Google and have seen that I need to do again sesssion_name()
and session_start()
in the second file to get access to the username.
TL;DR
Do I always need to do session_name()
and session_start()
on every file I want to get access to the data of my session with a custom session name?
I can clarify some things if it's unclear; might not be easy to understand.
You'll either need to run session_name()
on every file that needs access to the custom session, store the logic in a separate include file which is included within all relevant files, or change PHP's default session name via the session.name
configuration value.
Without specifying session_name()
in each case, PHP won't know that you want it to use a different name, and instead, default to the value from session.name
.