PHP session variables not preserved with ajax - php

I have a one page website that uses AJAX to load new php files and update the display.
I start my php session on the main page but when I use ajax to update inner html I need those session variables for the new php file being loaded.
This post is similar to this one: PHP Session Variables Not Preserved . But I checked and my php.ini has session.use_cookies = 1
Main Page PHP:
<?php
session_start();
if(isset($_SESSION['views']))
{$_SESSION['views']=$_SESSION['views']+1;}
else
{$_SESSION['views']=1;}
?>
After User Input I use ajax to call a php file and load a subsection of the page:
<?php
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
Can someone please tell me what important step I am missing? Thank you.
Update: After adding session_id() call to both the main and sub pages I see that both pages have the same Session_ID. However it still cannot pull the session variable and if i do assign it a value the two same name session variables stay independent of one another.
Answer to the question that this question created: I found that I had to set a static session_save path in my php.ini file. With most paid webhosting services they just have a default container for sessions but it is affected by load balancing. What a releif.

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";}
?>

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

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.

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're trying to use existing session data from your application in an ajax call. To do that, change how you're calling session_start like so:
// With ajax calls
if (session_status()==1) {
session_start();
}
When making ajax calls to php scripts that need existing session data, use session_start after session_status.
http://php.net/session_status

Need to initialize the session before you trying to login through ajax call.
session_start();
Initialize on the top of the page from where you start the login ajax call.
So that the SESSIONID will be created and stored the browser cookie. And sent along with request header during the ajax call, if you do the ajax request to the same domain
For the successive ajax calls browser will use the SESSIONID that created and stored initially in browser cookie, unless we clear the browser cookie or do logout (or set another cookie)

Related

App using old session file after session_regenerate_id()

session_start();
$_SESSION['user_id'] = 0;
session_regenerate_id();
$_SESSION['user_id'] = 5;
After running the following code, why is my $_SESSION['user_id'] still 0 when I access it later? Am I misunderstanding how session_regenerate_id() is supposed to work? Or is it an issue that I need to address elsewhere?
I can see that two session files have been created in C:\xampp\tmp, but I don't understand why the old file is being used.
My example is me trying to understand why I could not access $_SESSION['user_id'] that I would set after running session_start and session_regenerate_id at the very beginning of my .php file:
session_start();
session_regenerate_id();
$_SESSION['user_id'] = 9; // i am unable to access this because my app is using the old file
Appreciate any help with this.
Didn't you check the session.use_trans_sid php.ini option?
In my php.ini, I have session.use_trans_sid=0 and another suggestion mentioned i do the following as well session.use_strict_mode=1. Still not working after these two edits.
Note: i assume that they are 2 different https/http calls (the two
codes starting with session_start() ... ) Can you see what all is
stored in the 2nd file in the Session before and after you do the
session_start? you can do a print_r($_SESSION) and do it before you
regenerate as well I bet there is some code in between your lines that
you haven't shared, is doing something to the session_start
I actually simplified my code down to the example in my post, and you can see it here. This way, we are not worried about any other code.
I cleared my tmp folder and ran the code. Here are the resulting files with session_regenerate_id() commented out:
First File - https://pastebin.com/mBhQCrF3
addrelease.php output is 9 for 'user_id'
I commented out the line that sets the 'user_id' to 9 to see what happens next time I log on
Second File - https://pastebin.com/QNJ6S7sY
As expected, a new file with 8 as 'user_id'
Now I will clear the tmp folder (and restart server) again and do the same with session_regenerate_id() in the code. More specifically, this is what loginuser.php will run now:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 9;
$response['success'] = true;
$response['username'] = "test";
echo json_encode($response);
exit;
This time, since we regenerate the id, there should be two files after loginuser.php is finished. I can't tell which one was created first, but we can see that one has 'user_id' set as 9 while the other has 'user_id' at 8:
File 1: https://pastebin.com/ba1vAmjd
File 2: https://pastebin.com/H9kDfdvt
After this, the output given by addrelease.php once it's finished is 8.
With the following change to loginuser.php, we can also get an idea of what 'user_id' is before it exits and addrelease.php runs the second session_start() call:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 10;
$response['message'] = $_SESSION['user_id'];
$response['success'] = false;
$response['username'] = "test";
echo json_encode($response);
exit;
I clear tmp folder and restart servers again. This time, 'user_id' output is 10. So we can see that loginuser.php is using the correct file, while addrelease.php does not:
File 1: https://pastebin.com/7MpRMbge
File 2: https://pastebin.com/p6RUxH8F
Hopefully I have supplied enough in response to your comment.
EDIT: Also, I don't know if this is significant, but there is a another activity (dashboard activity) between my login activity and my add release activity that does not trigger a .php file.
I think i know the core issue and have the solution as well.
From the json_encode, i assume that some frontend is querying these php files and a json response is sent. So, the session is being written to multiple times.
After writing to the session, IN EVERY FILE that you write sessions to, but PER HTTP/HTTPS request, please do an explicit session_write_close() https://www.php.net/manual/en/function.session-write-close.php .
So, what i mean is that let us assume you have frontendpage1.php that has the html for the user. If you are writing to sessions in this file, do a session_write_close() at the end. Further, if, as a result of an ajax call or something, you have file1.php, file2.php and file3.php used, where they are all writing to the session, do session_write_close() at the end of the last write of the session.
I remember reading that this good practice when sessions are written to frequently.
I had a similar issue with sessions and this worked well
Remember to do a session_start() at the start of each unique browser request/ajax request
EDIT
2nd Option: I think you have a corrupt cookie PHPSESSID . If you try with a browser that doesn't have any cookies set (for the server that is hosting your files), i bet you see the right session values.
Another way to test is, use the same browser, but just add The only thing I can think of is a corrupt cookie PHPSESSID (the default) or whatever cookie you are using, but just add session_name("myStackOverFlowID"); before session_start(); in both these files. the new session_name is not highly recommended: it is just to test.
EDIT: another option
Do the session_write_close() before regenerating the ID
Thanks
Finally, we know that an Android App is involved!
Check if any part of the App code is storing cookies, etc., in cache
Track time using hrtime(true); (recommended instead of microtime for accuracy) see https://www.php.net/manual/en/function.hrtime.php
If possible, clear out the App data on that android phone and test on a different android phone as well
So, after seeing that session was working correctly on my PC browser, I assumed from there that the issue was perhaps purely with how I set up something in my code for the Android app.
As it turns out, my CookieJar implementation was non-persistent. Using PersistentCookieJar instead, I was able to have cookies persist between my activities on the app.
So for anyone having a similar issue, I would suggest reading through this thread and if nothing works, be sure to check your cookie management implementation for the app.

Issue with refreshing div with ajax [duplicate]

I have a one page website that uses AJAX to load new php files and update the display.
I start my php session on the main page but when I use ajax to update inner html I need those session variables for the new php file being loaded.
This post is similar to this one: PHP Session Variables Not Preserved . But I checked and my php.ini has session.use_cookies = 1
Main Page PHP:
<?php
session_start();
if(isset($_SESSION['views']))
{$_SESSION['views']=$_SESSION['views']+1;}
else
{$_SESSION['views']=1;}
?>
After User Input I use ajax to call a php file and load a subsection of the page:
<?php
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
Can someone please tell me what important step I am missing? Thank you.
Update: After adding session_id() call to both the main and sub pages I see that both pages have the same Session_ID. However it still cannot pull the session variable and if i do assign it a value the two same name session variables stay independent of one another.
Answer to the question that this question created: I found that I had to set a static session_save path in my php.ini file. With most paid webhosting services they just have a default container for sessions but it is affected by load balancing. What a releif.
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";}
?>
You need to start session session_start() in the other PHP file also, the one you are calling through AJAX.
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.
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're trying to use existing session data from your application in an ajax call. To do that, change how you're calling session_start like so:
// With ajax calls
if (session_status()==1) {
session_start();
}
When making ajax calls to php scripts that need existing session data, use session_start after session_status.
http://php.net/session_status
Need to initialize the session before you trying to login through ajax call.
session_start();
Initialize on the top of the page from where you start the login ajax call.
So that the SESSIONID will be created and stored the browser cookie. And sent along with request header during the ajax call, if you do the ajax request to the same domain
For the successive ajax calls browser will use the SESSIONID that created and stored initially in browser cookie, unless we clear the browser cookie or do logout (or set another cookie)

PHP session_id never the same on refresh

I am trying to use session_id() on some php pages, but the id changes between every file and it changes everytime i refresh the page. I placed the following script which should increment on ever reload, but it does not.
session_start();
if (!isset($_SESSION['hits'])) $_SESSION['hits'] = 0;
++$_SESSION['hits'];
echo '<p>Session hits: ', $_SESSION['hits'], '</p>';
echo '<p>Refresh the page or click <a href="', $_SERVER['PHP_SELF'],
'">here</a>.';
In my php.ini file, I have cookies turned on as well as set my save_path tp '/tmp'.
In the actual folder, there are session files... so i know it is not a file writing issue. I have also ensured that every file is utf-8 with bom to ensure consistency.
If there are any other solutions you can think of, please help me solve this. It is driving me insane.
Thanks!!!
The 3 possibilities I can think of for your situation are:
How are you calling session_id()? Include that code in your question. If you're calling it with any arguments it will override the session ID to whatever argument you passed.
Are cookies enabled in your browser? The session ID is sent to the browser as a cookie.
Are you calling session_destroy() at any point? This will delete the session data from the server and cause a new session to be started on subsequent pageviews.
That is because you are creating a new session every time you refresh the page. You must enclose your session start statement in a if.
if(session_id() == ''){
session_start();
}

Writing to a PHP Session Variable from Ajax

Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.

Problems accessing same SESSION variables from different files

I'm developing a site using Wordpress.
My permalink structure is set to show post/page name. So accessing a page called store will look like this: www.mysite.com/store/?some=arguments
In all my WP templates, I'm able to output all my SESSION variables using print_r($_SESSION);
Doing the same from a file called from jQuery.ajax only outputs some of the SESSION varaibles.
I've used the following code to see if the cookie path is same for both files, and they are:
$sessCookie = ini_get('session.cookie_path');
echo 'session.cookie_path: '.$sessCookie;
I also have this code in my files to make sure session is started:
if (!session_id())
session_start();
Why am I not able to output the same session variables from a WP template and a php file called from jQuery.ajax?
UPDATE
jQuery.ajax calls jquery.php file. At the top of this file, it has the following code:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php');
This code fires functions.php. In this file I have the following code:
function session_manager() {
if (!session_id())
session_start();
// Get variables in query string
$_SESSION['action'] = (isset($_GET['action']) ? $_GET['action'] : '');
$user_geo_data = get_geoip_record();
$_SESSION['user_geo_location'] = get_object_vars($user_geo_data);
}
When functions.php is fired from jquery.php, it seems that session_id() returns false, thus I create a new session.
Is there a way to keep using the same session?
UPDATE 2
It seems that WP config kills all GLOBAL variables when initialized.
http://wordpress.org/support/topic/wp-blog-headerphp-killing-sessions
Wordpress can use its own session handler, and overrides the default session handler to do so. So in essence you've got two different sessions, even though they share the same ID. The cookie path is merely how the client-side cookie operates. What you need to check is session_save_path(), and check if WP is running sessions through the database instead of the default file handler.
The reason two sessions are fired up is because the first one is browser-based (through a cookie) and the second one, with Ajax, is essentially server-side and doesn't have access to the session cookie.
The session cookie is where the session ID is stored and is used to identify an existing session. A server-side Ajax script doesn't have access to the browser's cookies, thus fires up a new session.
It can be worse if the main script uses an alternate session "save handler" than the Ajax script, resulting in two separate sessions, stored in two different places.

Categories