PHP session variables not preserved with ajax

In the case of using a paid web hosting service the default session save path is automatically set like this:

http://php.net/session.save-path
session.save_path = "/tmp/"

You need to place the static path to your root folder there.


You need to start session session_start() in the other PHP file also, the one you are calling through AJAX.


I think you're missing session_start() on the page that Ajax calls.

You need:

<?php
session_start();
if(isset($_SESSION['views']))
    { echo "Views: " . $_SESSION['views'];} 
    else 
    { echo "Views: NOT SET";}
?>

I ran into what i thought was the same issue when running PHP 7 on IIS Server 2012 today.

I had added:

if(!isset($_SESSION)) 
{ 
    session_start(); 
} 

to the start of each AJAX file but kept recieving the following PHP Notice:

PHP Notice: A session had already been started - ignoring session_start()

A bit of searching lead me to this thread which pointed me in the right direction to resolving the issues I encountered. Hopefully the following information will assist others encountering the same issue.

After checking the session.save_path value was set, in my case C:\Windows\Temp, I thought it best to check the folder permissions match those of the user account I was running IIS under.

In my case it turned out that the directory I had nominated for session storage (in php.ini) did not have the same user (security permissions) assigned to it as the one which was running the IIS site.

Interestingly sessions worked fine when not using AJAX requests prior to me adding the new user permissions. However AJAX did not pick up the session until I had corrected the permissions issue. Adding the same user account that IIS is running under immediately resolved this issue.