I have observed my php application behaving rather strangely on the server that it is running on. When a user first visits the application, and clicks on a link with an absolute path, the session data is cleared.
I have recreated the problem as simply as possible. The code can be found below.
I have solved this problem by removing all absolute links in my application, I am simply looking for an explanation of this behavior.
To recreate the problem:
- click ‘login’
- click ‘relative link’ and observe that the session still has the ‘logged_in’ variable set
- click ‘absolute link’ and observe that the session data appears to be missing
- click your browser’s back button and observe that the session data has returned
- click ‘absolute link’ and observe that the session data is missing again
- click ‘home (relative link)’ and observe that session data is missing this time
- click ‘login’ to reset the session data
- click ‘absolute link’ again and observe that the session data was not cleared this time
Some important things to note:
- This is not a problem locally on my
mac running MAMP with php 5.3.2,
but is a problem on a server with
php 5.2.14 and a different server running 5.3.2 - clicking the absolute link, and then the relative home link without login prevents the problem from ever occurring once you do log in.
- once the problem is solved by the method just mentioned, it can only be recreated by navigating to a different domain, clearing your browser’s cache and navigating back. Clearing the cache without leaving the page will not work.
- this is also a problem if using a absolute path when redirecting using header(‘Location: …’)
index.php:
<?php
session_start();
print_r($_SESSION);
?>
<br/><a href="http://www.myserver.org/page.php">Absolute link</a>
<br/><a href="page.php">Relative link</a>
<br/><a href="login.php">Log in</a> | <a href="logout.php">Log out (reset session)</a>
page.php:
<?php
session_start();
print_r($_SESSION);
?>
<br/><a href="index.php">Home (relative link)</a>
login.php:
<?php
session_start();
$_SESSION['logged_in'] = true;
header('Location: index.php');
logout.php:
<?php
session_start();
$_SESSION = array();
session_destroy();
header('Location: index.php');
Solved:
Thanks to Nouveau for pointing out that a cookie can only be used for one domain and The Scrum Meister for asking if I always access the site with a www.
The problem was created by starting at http://myserver.com and following the link to http://www.myserver.com
The Session was initialized for http://myserver.com and then again for http://www.myserver.com