Amir E. Habib
Amir E. Habib

Reputation: 73

Accessing PHP session variable from different paths

I am facing a very weird problem in PHP sessions, here are the facts:

Creating a session variable code - mydomain/a/b/c/create_session.php

<?
    session_start();
    $_SESSION['test'] = "Hello World";
?>

Reading the session variable read mydomain/a/b/c/read_session.php

<?
    session_start();
    echo $_SESSION['test'];
?> 

The Problem

When I access the read_session.php code from within the same URL it works fine. But when I'm trying to read the session variable from a different path, it doesn't work.

Examples

mydomain/a/b/c/read_session.php - works!

mydomain/a/b/read_session.php - works!

mydomain/a/read_session.php - works!

mydomain/read_session.php - doesn't works!

mydomain/d/read_session.php - doesn't works!

Upvotes: 4

Views: 6215

Answers (4)

Gumbo
Gumbo

Reputation: 655319

Cookies (and thus cookies for session IDs) can be bound to certain domains and paths. The default configuration of PHP’s session ID cookies is to bound the cookies to the current domain (session.cookie_domain) and the path / (session.cookie_path).

Maybe your session configuration differs from the default configuration insofar as the cookie’s path is set to /a so that the cookie on only valid in /a as well as those paths where /a is a proper path prefix (i.e. /a/…).

Try to change the cookie path to /:

ini_set('session.cookie_path', '/');

Upvotes: 0

jacobangel
jacobangel

Reputation: 6996

As Briedis says, you might not be using the same domains. They have be the same.

Make sure you check your session.cookie_paths. It is possible your configuration settings are setting the cookie's path to "/a". In that case, the functionality you describe would occur, because there would be a path mismatch.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237905

You could try using session_set_cookie_params, in case you have a configuration setting muddling things up somewhere:

session_set_cookie_params(0, '/');
session_start();

You can configure cookies to be usable only on certain paths on the domain. It's possible that that has happened here. NB that if this is the issue, the best way to fix it is by changing the value in php.ini:

session.cookie_path = "/"

Upvotes: 2

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

That couldn't be the problem.

Domains need to be exaclty the same (cookie policy), that means http://www.domain is not the same as http://domain

Upvotes: 1

Related Questions