Jump to content

Recommended Posts

Hi,

 

I am building a website using PHP. By default the SESSION is kept active for 24(1440 seconds) minutes of inactivity.

 

What i want is to refresh the SESSION as soon as the user interacts with the website (movement of the mouse, click on links inside the website, etc.)

 

The way i am trying to refresh the session is by calling PHP script named refreshSession.php with AJAX as follow:

 
 $.ajax({
     cache: false,
     type: "GET",
     url: "refreshSession.php"
 });

and the PHP script goes as follow:

 

refreshSession.php

<?php

   session_start();

   echo 'test';

?>

But the session does not refresh.

 

The only way to refresh the session is to reload the page.

 

What am i doing wrong? Any suggestions?

 

Regards,

 

Christos

 

First, confirm that in fact your ajax request is in fact making a request to the server.  Are you getting the "test" response?  Also, consider putting a syslog(LOG_INFO,"bla"); in your server script to confirm.

 

Also, make sure there are not any cross domain issues.  I wouldn't expect so if your requests are actually accessing the server.

 

Consider changing from GET to POST as you are actually changing the state of the server.

 

Next, make sure your server is receiving the same session cookie whether a page reload or ajax request.  Unless you changed the cookie name, it should be $_COOKIE['PHPSESSID'].

 

Confirm that your main page reloads are setting up the session the same way.

 

If all else fails, you might want to look into the HTTPOnly flag: https://www.owasp.org/index.php/HTTPOnly

Edited by NotionCommotion

First, confirm that in fact your ajax request is in fact making a request to the server.  Are you getting the "test" response?

Yes i see the "test" inside the response window.

 

Also, consider putting a syslog(LOG_INFO,"bla"); in your server script to confirm.

 

Also, make sure there are not any cross domain issues.  I wouldn't expect so if your requests are actually accessing the server.

No cross domain requests. I request a script that is on my domain.

 

Consider changing from GET to POST as you are actually changing the state of the server.

Done that. No luck.

 

Next, make sure your server is receiving the same session cookie whether a page reload or ajax request.  Unless you changed the cookie name, it should be $_COOKIE['PHPSESSID'].

My session name is changed in both WHM and php.ini from PHPSESSID to CUSTOMSESSID.

 

Confirm that your main page reloads are setting up the session the same way.

It seems that its setting it the same way.

 

If all else fails, you might want to look into the HTTPOnly flag: https://www.owasp.org/index.php/HTTPOnly

Done that. No luck.

Try putting your full domain on the AJAX method. Make sure to be consistent with the www. prefix. If you initially load your site with www., make sure to include it. If you don't, make sure not to include it.

Done that. i used all possible URLs. With http, https, www., whithout www. Still the same result..

Please do the following:

 

1. Visit your site with Google Chrome.

2. Press ctrl+shift+i, or click the hamburger menu on the top right of Chrome and go to Tools -> Developer Tools.

3. Click the Network tab, and then click the "Clear" icon right underneath the Network tab.

4. Trigger your AJAX call, so that it appears in the Network area.

5. Click on the new entry.

6. On the right hand side of the Network pane will be detailed information about the request to your server. Under request headers, it should list the cookies that were sent with the request. Please verify that your session cookie is being sent.

 

Here is an example: vyOclfQ.jpg

Edited by scootstah
But the session does not refresh.

 

 what sort of symptom or error are you getting that leads you to believe that the last accessed time of the session data isn't being updated.

 

also, do you have php's error_reporting/display_errors/log_errors turned full on so that any session_start() error with the refreshSession.php file would be displayed/logged?

Please do the following:

 

1. Visit your site with Google Chrome.

2. Press ctrl+shift+i, or click the hamburger menu on the top right of Chrome and go to Tools -> Developer Tools.

3. Click the Network tab, and then click the "Clear" icon right underneath the Network tab.

4. Trigger your AJAX call, so that it appears in the Network area.

5. Click on the new entry.

6. On the right hand side of the Network pane will be detailed information about the request to your server. Under request headers, it should list the cookies that were sent with the request. Please verify that your session cookie is being sent.

 

Here is an example: vyOclfQ.jpg

Thanks for this! I am testing it in a while and i will let you know!

Please do the following:

 

1. Visit your site with Google Chrome.

2. Press ctrl+shift+i, or click the hamburger menu on the top right of Chrome and go to Tools -> Developer Tools.

3. Click the Network tab, and then click the "Clear" icon right underneath the Network tab.

4. Trigger your AJAX call, so that it appears in the Network area.

5. Click on the new entry.

6. On the right hand side of the Network pane will be detailed information about the request to your server. Under request headers, it should list the cookies that were sent with the request. Please verify that your session cookie is being sent.

 

Here is an example: vyOclfQ.jpg

 

 

I did this. What i see inside REQUEST HEADERS is:

 

Cookie: CUSTOMSESSID: mmadfjdjfdjfiwer239434....

 

Inside RESPONSE HEADER at the other hand i dont see anything regarding the cookie.

 what sort of symptom or error are you getting that leads you to believe that the last accessed time of the session data isn't being updated.

 

also, do you have php's error_reporting/display_errors/log_errors turned full on so that any session_start() error with the refreshSession.php file would be displayed/logged?

 

Maybe i got it wrong at the first place..

 

What i did to see if the session timeout is refreshing, was to change the value of session.gc_maxlifetime from 1440 to 20 seconds.

 

At the same time i used setInterval() function to send an AJAX request every second to the refreshSession.php.

 

My thinking was that if the AJAX request is refreshing the SESSION every second, and the SESSION is cleaned up every 20 seconds (in other words refreshing frequency > clean up frequency) then the SESSION would never cleaned up by the garbage collection process.

 

It turns out that even if i reload the page using CTRL+R the session is not refreshed..

 

Whats is wrong? Should be the SESSION refreshed if the user performed some action like refreshing the page?

My thinking was that if the AJAX request is refreshing the SESSION every second, and the SESSION is cleaned up every 20 seconds (in other words refreshing frequency > clean up frequency) then the SESSION would never cleaned up by the garbage collection process.

 

 

^^^ yes, that's correct. the session_start() statement updates the last accessed time of the session data file, that prevents the garbage collection from deleting that particular session data file, when garbage collection actually runs (it runs randomly based on the two probability values.) even if the session data file is older than the session.gc_maxlifetime value, if it hasn't been deleted yet by the garbage collection, if you execute a session_start() it will update the last accessed time of the session data file and the session will still exist (the garbage collection probability calculation runs as part of the session_start(), but after the session data file has been read.)

 

the session is not refreshed..

 

 

again, what sort of symptom or error are you getting that leads you to believe that the session is not refreshed.

 

and what about the php error settings i asked/suggested and are there are any errors occurring at the session_start() statement?

Edited by mac_gyver
Cookie: CUSTOMSESSID: mmadfjdjfdjfiwer239434....

 

 

if you are setting custom session and session-cookie settings, you must set the same settings before EVERY session_start() statement. otherwise, you are creating/resuming different sessions.

if you are setting custom session and session-cookie settings, you must set the same settings before EVERY session_start() statement. otherwise, you are creating/resuming different sessions.

 

I have altered the value of session.name inside php.ini from PHPSESSID to CUSTOMSESSID. Do i need to set this before session_start() using session_name('CUSTOMSESSID') as well?

 

and what about the php error settings i asked/suggested and are there are any errors occurring at the session_start() statement?

 

I have used the following code after session_start() inside refreshSession.php:

 

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

Where should i see the error (if any)?

 

Also "again, what sort of symptom or error are you getting that leads you to believe that the session is not refreshed.":

 

The session.gc_maxlifetime is set to 20 seconds. If i reload the page, that counter should be 0. If 10 seconds pass and then i reload the page, then the counter should again go to zero. But in my case, regardless how many times i reload the page, the session lasts 20 seconds. If i reload the page at the 21st second then the page logs out.

I am recapping here:

 

When the user enters his credentials to the login page form, a $_SESSION['logged_in'] is turned to TRUE [ofcourse if credentials are correct]. While on main page i check if this variable is TRUE and proceed. If not i redirect the user to login page again.

 

So when the gc clears the SESSION, this variable is not equal to TRUE, so the user is redirected to login page.

 

My purpose is to find a way to refresh the SESSION timeout if the user interacts with the webpage (click, mouse movement, etc.). Because right now the SESSION lasts only as long as the session.gc_maxlifetime lasts (24 minutes), regardless of how the user interacts with the website.

 

ps: i dont want to increase the maxlifetime value, i just need a way to refresh it on user's interaction

I have altered the value of session.name inside php.ini from PHPSESSID to CUSTOMSESSID. Do i need to set this before session_start() using session_name('CUSTOMSESSID') as well?

 

 

that should work (just in the php.ini), unless you are doing this in a local php.ini (not the master one) and you are on a server where the php.ini is per folder, and you have multiple folders involved for your code that sets/references the session variables and the code where your refreshSession.php is at that's trying to refresh the session. this doesn't appear the be the case (since the ajax call apparently requests a/the correct refreshSession.php flie), but are all the .php files involved in the same folder and is the php.ini that you put the session name setting in the master php.ini or a local one (in a folder on your server)?

 

there's nothing technically wrong with what you are trying to do. if it isn't working, it's because there's something that, you, your code, or your server/php are doing that's preventing it from working. all the suggestions we have been making (lol, did you really put the php error setting code after the session_start() statement, when it's stated purpose was to see if the session_start() was producing an error) are to get you to investigate what might be happening in order to narrow down the many possibilities to just a few so that the troubleshooting can target the actual problem.

 

one thing we haven't suggest yet is for you to add var_dump($_SESSION) in the refreshSession.php code (after the session_start() statement), to see if the expected session variables exist. it may very well be that refreshSession.php is doing what it is supposed to do, resuming the correct session, but something else, such as a logic error in your code, is causing the logout to occur.

 

another thing you need to do in all the pages that set/reference session variables and in the refreshSession.php code, is to echo session_id() (after the session_start() statement). the session id should be the same on all pages, otherwise you have multiple sessions.

 

to determine if you have multiple sessions, you will have multiple session cookies in your browser, with different names (if your php.ini setting isn't applying to all your .php files), content (the session id), path, and/or domain values.

 

another thing to try, is to delete all the relevant cookies in your browser and start over. you may have session cookies left over (assuming you have a positive time set for the session cookie lifetime) from previous testing that are causing php to resume/start a session that doesn't match your current session name/cookie settings.

 

lastly, for hard to debug problems, you will likely need to post (less any database credentials) the actual code needed to reproduce to the problem, to allow someone to be able to see if your code does have a logic error in it that's causing the problem or to reproduce the problem elsewhere to see if the problem is something to do with your server/php.

Edited by mac_gyver
It turns out that even if i reload the page using CTRL+R the session is not refreshed..

 

 

i'm assuming that means the page that's giving you the symptom of the session expiring/of being logged out. if so, it sounds like the session_start() on that page isn't actually working (there would be php errors) or a logic error in your code is clearing the session variables. and that even brought another suggestion to mind, of a header() redirect that doesn't have an exit/die statement after it and your php that continues to run, after the header() statement, is clearing the session variables.

 

at this point, it's going to take seeing all the actual code involved that reproduces the problem, from start (the login code) to the end.

Edited by mac_gyver

To expand on mac_gyver's suggestions, please pop the two attached scripts onto your server. Afterwards, open test_login.php in your browser. It should create a new session with two keys, and print some session information. Then, in the same window, open test_refresh.php. The refresh should update the $_SESSION['last_access'] value and also print some session information. In your next reply, please post the output from both of these scripts. Also, try continually refreshing the test_refresh.php to see if the session still expires after 20 seconds.

test_refresh.php

test_login.php

that should work (just in the php.ini), unless you are doing this in a local php.ini (not the master one) and you are on a server where the php.ini is per folder, and you have multiple folders involved for your code that sets/references the session variables and the code where your refreshSession.php is at that's trying to refresh the session. this doesn't appear the be the case (since the ajax call apparently requests a/the correct refreshSession.php flie), but are all the .php files involved in the same folder and is the php.ini that you put the session name setting in the master php.ini or a local one (in a folder on your server)?

 

there's nothing technically wrong with what you are trying to do. if it isn't working, it's because there's something that, you, your code, or your server/php are doing that's preventing it from working. all the suggestions we have been making (lol, did you really put the php error setting code after the session_start() statement, when it's stated purpose was to see if the session_start() was producing an error) are to get you to investigate what might be happening in order to narrow down the many possibilities to just a few so that the troubleshooting can target the actual problem.

 

one thing we haven't suggest yet is for you to add var_dump($_SESSION) in the refreshSession.php code (after the session_start() statement), to see if the expected session variables exist. it may very well be that refreshSession.php is doing what it is supposed to do, resuming the correct session, but something else, such as a logic error in your code, is causing the logout to occur.

I did. The variables i store inside the session are visible inside var_dump($_SESSION).

 

another thing you need to do in all the pages that set/reference session variables and in the refreshSession.php code, is to echo session_id() (after the session_start() statement). the session id should be the same on all pages, otherwise you have multiple sessions.

I have tested this in the refreshSession.php and inside the main-page.php. Both session ids were identical.

 

to determine if you have multiple sessions, you will have multiple session cookies in your browser, with different names (if your php.ini setting isn't applying to all your .php files), content (the session id), path, and/or domain values.

If i go to inspect element in Chrome, EditThisCookie tab,  i see 3 cookies: 2 for Google Analytics and 1 from my website (CUSTOMSESSID). Nothing else.

 

another thing to try, is to delete all the relevant cookies in your browser and start over. you may have session cookies left over (assuming you have a positive time set for the session cookie lifetime) from previous testing that are causing php to resume/start a session that doesn't match your current session name/cookie settings.

Again inside inspect element, i go to network tab, right click and Clear Browser cookies. I did this with no luck..

 

lastly, for hard to debug problems, you will likely need to post (less any database credentials) the actual code needed to reproduce to the problem, to allow someone to be able to see if your code does have a logic error in it that's causing the problem or to reproduce the problem elsewhere to see if the problem is something to do with your server/php.

 

All this time i though that by reloading the webpage the session timeout is refreshed...

All this time i though that by reloading the webpage the session timeout is refreshed...

That is correct. Every time session_start() is called, the session TTL is restarted.

 

My test for you above will determine if you have some issue with your server config, or some issue in your code such as a logic problem or something else.

To expand on mac_gyver's suggestions, please pop the two attached scripts onto your server. Afterwards, open test_login.php in your browser. It should create a new session with two keys, and print some session information. Then, in the same window, open test_refresh.php. The refresh should update the $_SESSION['last_access'] value and also print some session information. In your next reply, please post the output from both of these scripts. Also, try continually refreshing the test_refresh.php to see if the session still expires after 20 seconds.

This is the output for each script:

 

login_test.php

Session ID: aip20b2ha1qmpvg2pnvk67n5btuh2uvbubfkj7qaoornq8mqmsoffmcmq200t7b4g02vb83nu4bn892rshc7pglcttgfjqa6p01t5l0
Session Data:Array
(
[hashed_token] => eb5c2d98795f5cffa55ab0ae7a07cd8158329867a008245fabccdf843280b2dc
[logged_in] => 1
[last_access] => 1436452752
)


You have been logged in!

test_refresh.php

Session ID: aip20b2ha1qmpvg2pnvk67n5btuh2uvbubfkj7qaoornq8mqmsoffmcmq200t7b4g02vb83nu4bn892rshc7pglcttgfjqa6p01t5l0
Session Data:Array
(
[hashed_token] => eb5c2d98795f5cffa55ab0ae7a07cd8158329867a008245fabccdf843280b2dc
[logged_in] => 1
[last_access] => 1436452755
)


The session has been refreshed!

Refreshing the test_refresh.php would not change the session ID (i assume that if the session ID stays the same then the session has not expired).

 

Even if i refresh the test_refresh.php after 20 seconds i still see the same sessionID.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.