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.

What’s better for newbies to learn first PHP or MySQL?

It’s a good question for newbies to have, where to start?

What comes first PHP or MySQL?  The chicken or the egg?

You can learn both independently, but if you have no experience with either, I think it’s best to start with PHP.   Pretty quickly as you work through tutorials you will encounter MySQL.  They really go hand in hand for many applications.

If you have zero experience, there are other things you will need to learn also if you haven’t already…

  • HTML
  • CSS
  • Javascript / JQuery

How do you include frequently used code in another PHP file?

Q. How do you include PHP files in other PHP files?

– Useful for including your database connection across all pages that need it.
– If you have written some functions once and want to reference them in other pages.
– Also commonly used to keep consistent header and footer parts of your pages, by including them.

A. You can use the include and include_once statement, you can also use the require or require_once statement, all have the same effect of including your code from one PHP file into another PHP file.

<code>include (“my_file_to_include.php”);</code>

(PHP Manual)

This saves you time by re-using your PHP code and makes it easier to maintain.