How to access PHP session variables from another PHP page

​​

One of my subscribers sent me an email asking me about problems he was having with sessions.

He had already created a session variable in one PHP file.

Now he had a second PHP and wanted to access the session variable in it.

However he was struggling to access his session variable.

He found the only way to access it, was by including the first PHP file in the second PHP file.

This is a common problem which seems extremely frustrating.

A session and it’s variables should be shared with all the PHP pages in your project right?

The session is, but you need to know how to access the session and it’s variables in another PHP page.

So I asked him if he had called the PHP function session_start()

Calling this function is necessary in every PHP page where you want to use a session variable.

The session_start() function will either resume an existing PHP session or start a new one if there isn’t one existing already.

He responded back to me after updating his php code with the call to the session_start() function.

After updating his code he was able to access his session variable in his second PHP page, without including the first PHP file.

So every time you need to access a PHP session variable don’t forget you need to call session_start() first.

If this post helped you please subscribe and save yourself more development time with my helpful PHP web development tips delivered to your inbox weekly.