Reputation: 123
I was wondering how I would pass something using a session between pages that are in two separate directories. For example, if I had the following code, what would I need to add to make it work?
Page 1: directory\directory1\directory2\Page1.php
session_start();
$_SESSION['example'] = '123';
Page 2: directory\dir1\dir2\Page2.php
session_start();
echo $_SESSION['example'];
Upvotes: 0
Views: 78
Reputation: 29037
First of all, check if session-cookies are properly set. Some problems (e.g. Headers already sent) may cause your session cookie to not be set.
If this is working properly, you may have to change the session cookie parameters via session_set_cookie_params
By setting the second parameter (path) to /
, the session cookie is valid for the root of your website and all subdirectories.
Example
session_set_cookie_params(0, '/');
The same settings can also be set in your php.ini or via ini_set()
. See Session configuration
Note:
I'm not sure if these settings have any effect if session.autostart
is enabled, in which case the cookie-header may already be sent before the changes are made.
Upvotes: 1
Reputation: 16495
You do not have to session_start()
in each page. Just write that, in a single file and share that file between the pages you want to hold the session in.
So, if you have page1.php
and page2.php
and session.php
You can create session either in page1.php and check it in page two like: echo var_dump($_SESSION)
and vise-versa
Upvotes: 1
Reputation: 562
Your code should work if these pages are served within the same domain.
Upvotes: 1