Prevent PHP SESSION expiration using AJAX - php

I know that this is a question asked several times but I have search a lot to find a solution with no luck. Some of the URLs i have visited were:
https://xpapad.wordpress.com/2010/06/19/preventing-session-expiration-with-ajax/
Prevent session expired in PHP Session for inactive user
PhP Session does not refresh using AJAX
Refresh PHP SESSION var after AJAX request
Most of them suggest that in order for the SESSION to refresh you must place an AJAX request that is targeting a PHP script that starts a session:
window.setInterval( function() {
$.ajax({
cache: false,
type: "GET",
url: "refreshSession.php",
success: function(data) {
}
});
}, refreshTime );
In the refreshSession.php you can do something like session_start() .
Unfortunately by doing this the SESSION does not refresh. Any ideas why?
PS: Before calling session_start() i am calling my custom session name like session_name('CUSTOMSESSID').
Thanks,
Christos

Related

Handling redirection when session timeout via ajax

I have a view function which only logged in user can see. When clicking the view button, it will send an ajax request to PHP function and return back the result which then be displayed in the html. The issue is, if the user idle for too long, when they suddenly come and click the view button again, the display (where the ajax response supposed to be displayed) will show the login page instead of the requested data.
It was because the PHP session has expired. I want to prompt an alert to tell them about this timeout session and redirect them to the login page instead but I don't know how to do that cause I tried to console.log() the PHP session and it's still showing all of the session. I am convinced that this is something like a memory or a flash cache (not very sure).
QuickView = (pc_no) =>{
$.ajax({
type: 'get',
url: '<?= $ajax_url; ?>view-receipt/'+pc_no,
data: { pc_no:pc_no },
success: function(res){
console.log(<?= json_encode($this->session->userLogged); ?>)
<?php if($this->session->userLogged){ ?>
$('#receipt-inline-view').html(res);
<?php } else { ?>
if(alert('Your session has expired. Please re-login.')){
window.location.href = '<?= base_url(); ?>';
}
<?php } ?>
}
})
}
Based on the code above, the user session will be stored in $this->session->userLogged. After PHP timeout, it should be cleared. But from console at ajax there, it's still showing the session even after it gets cleared up. Hence, the redirection also cannot be triggered.

Is there a better way to check for expired SESSIONS when using JQuery?

I've only been using JQuery for a few weeks. And in this short time I've noticed that, when a SESSION expires, my Login page loads inside the already-loaded document. This was never an issue until I started using JQuery. So I'm thinking that, since I've rewritten all my documents for JQuery to make the calls to PHP, my lone SESSION check is being pulled into the JQuery PHP calls instead of redirecting to the login page. When it does this, a quick page refresh will send the user to the login page. But it sure looks cheesy.
So, my thinking on this (and I hope I'm wrong) is to put
if ($_SESSION["memberid"] == "") {
header("Location: wslogin.php");
exit();
}
inside every PHP block called by JQuery. Maybe this wld be what's now needed since I'm using JQuery. Before JQuery, all my work was inside <form> tags, and the pages reloaded with every action. And an ended SESSION was always sent to the login page. I'm not the best explainer in the world, but I hope someone understands this and has a solution. Thanks.
Send 401-Unauthorized status code from requested page if session expired. Then capture status code in your client AJAX call.
JavaScript
$.ajax({
data: {},
dataType: 'json',
success: function(data) {
// do whatever here
},
type: 'post',
url: 'load_data.php',
error: function(XMLHttpRequest, textStatus, errorThrown) {
// XMLHttpRequest.responseText has your json string
// XMLHttpRequest.status has the 401 status code
if (XMLHttpRequest.status === 401) {
location.href = 'login.php';
}
}
});
PHP
header('HTTP/1.1 401 Unauthorized', true, 401);
Reference
HTTP Status Codes
PHP Session, with php control your session
<?php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header('location:logout.php');
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (empty($_SESSION['username'])) {
header('location:logout.php');
}
?>
Simply you may keep this on header of your template page so every time php check the session timing even you may improve this...

How to keep session alive without reloading page?

I have a strange problem in my online test management system.
Some users in the test form (test.php) need long time to answer the question and submit the form.
After submitting the form the session is expired and user must login again
this is not a code problem
I set this value in top of all pages
ini_set('session.gc_maxlifetime', 18000);
Is there a way to refresh the session evrey 10 minutes without reloading the page in test form to prevent session expire?
Please help me
Thanks
You can use javascript XHR, or as others call it, AJAX.
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/
Using ajax you can call a php script that refreshes your session every 10 minutes. :)
This is as far as i can go to "exact".
javascript
var refreshSn = function ()
{
var time = 600000; // 10 mins
setTimeout(
function ()
{
$.ajax({
url: 'refresh_session.php',
cache: false,
complete: function () {refreshSn();}
});
},
time
);
};
// Call in page
refreshSn()
refresh_session.php
<?php
session_start();
// store session data
if (isset($_SESSION['id']))
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
?>
Anyway, another solution would be to extend the session time for the test page only using
the solution presented here
How do I expire a PHP session after 30 minutes?
All you need is this (uses jQuery for the $.post):
JavaScript (put this inside your onload-function or something)
setInterval(function(){
$.post('path/to/refresh_session.php');
},600000); //refreshes the session every 10 minutes
refresh_session.php
<?php
session_start();
// if you have more session-vars that are needed for login, also check
// if they are set and refresh them as well
if (isset($_SESSION['token'])) {
$_SESSION['token'] = $_SESSION['token'];
}
?>
The biggest change is in the JavaScript--you don't need a whole function, just one line.
EXTRA INFO
Although I think it's enough to just call session_start() in the php, if I read this right (http://nl3.php.net/function.session-start):
The read callback will retrieve any existing session data (stored in a
special serialized format) and will be unserialized and used to
automatically populate the $_SESSION superglobal when the read
callback returns the saved session data back to PHP session handling.
And during testing I only put the above code on my visitor page, and not on the admin page. But I had both pages open in the same browser (Chrome), and the admin page stayed logged in as well, at least for over an hour (didn't check any longer).
BUT, I don't know if it still works if you only use session_start(), without manually refreshing any session-var at all..
Either way, I like to be sure that the session-vars I need are really still there:)
Javascript:
function doStayAlive() {
var request = new XMLHttpRequest();
request.open('GET', 'stayalive.php', true);
request.send();
}
timerStayAlive = setInterval(doStayAlive, 600000); // 10 minutes
PHP: (stayalive.php)
<?php
session_start();
http_response_code(204);
?>
There is no need to "touch" session variables

Create a session before an ajax call

I have this website where I can interact with the web both as a logged or anonymus user. When I click a link I call an ajax function:
you click here:
<a id="alcrearuta" class="'.$row->urlamigable.'" href="#">añadir a ruta</a>
This is my ajax function:
var valor=$("#alcrearuta").attr('class');
$("#alcrearuta").click(function(){
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "urlamigable=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
The thing is I have two possibilities: either a logged user clicks the link and the ruta.php does its stuff on the database considering the userid that's set in the session or I have an anonymous user that wants to do something similar.
In my ruta.php I have:
if(!empty($_SESSION['Username'])){
//Insert stuff on DB
}else{
//I wish I could create the session here but I can't since it's an ajax call
}
What I need is at some point between the click in the link and the end of the ajax function I can set my $SESSION['Username'] variable to get a new value (since the user it's not logged in, it's currently empty and thus my inserts on the database not working)
if you want to use sessions in php, your php script (ruta.php) schould start with
session_start();
from that point you can assign any variable to $_SESSION['Username']
$_SESSION['Username'] = something_to_generate_a_Username;
Just like any other server request.
You could use jquery cookie library to create a session cookie.
$.cookie("Username", "NOTLOGGEDINUSER");
https://github.com/carhartl/jquery-cookie
http://www.electrictoolbox.com/jquery-cookies/
and in beforeSend for Ajax, you can check if username cookie exists, other wise, create the cookie with "NOTLOGGEDINUSER"
Maybe on the click do another AJAX call just to set the SESSION?

Prevent session expired in PHP Session for inactive user

I have a problem with my application: my application has many forms and need about 1 hour to finish this form because the form is dynamic (can add other forms). The problem is: the session of my web server is 24 minutes. When user fill the form, they spent so much time and the session timed out because server recognize that the user is inactive. It's very annoying when form submitted, most data was lost and the user is returned to the login page. I have tried to make my session expired in 10 hours with this code:
ini_set('session.gc_maxlifetime', '36000');
But it's not working in my server, is it possible my server preventing ini_set() function?
So, what should I do for solving this problem? Can I prevent session timeout so that the session can be expanded to 10 hours? Or can I disable session expiration?
Thanks
Instead of setting the time in ini to a fixed length, remind that session timeout is reset on reload. So create some ajax code that does a request every 5 minutes or so to a file (image or smth). This way the timer is reset every 5 minutes and users can spend a day filling out your forms.
Here an example to prevent session timeout by using a jQuery Ajax call:
var refreshTime = 600000; // every 10 minutes in milliseconds
window.setInterval( function() {
$.ajax({
cache: false,
type: "GET",
url: "refreshSession.php",
success: function(data) {
}
});
}, refreshTime );
in the refreshSession.php you can do something like session_start()
I have had the same problem in the past. What I did to get around this was to place these two functions in a config file which gets included in every file.
session_set_cookie_params(86400);
ini_set('session.gc_maxlifetime', 86400);
and just for safe measure this line in my .htaccess file
php_value session.gc_maxlifetime 86400
Changing session.gc_maxlifetime using ini_set should work as long as you change the option before calling session_start. So doing the following should work:
ini_set('session.gc_maxlifetime', 36000);
session_start();
You can also change that option in other contexts (see ChazUK’s answer).
But I wouldn’t set the cookie’s lifetime to a fixed value but make the session’s cookie a real session cookie that lasts until the browser session is ended (i.e. on browser close). You can do this by setting session.cookie_lifetime to 0.
Do also consider that PHP’s session expiration model is a little quirky as the lifetime calculation is based on the session data’s last modification date.
How long a session cookie lasts is set when you create the session cookie. If you use the setcookie method, an argument of the method is the LENGTH for which you would like the cookie to last.
Please refer to the PHP manual on the method for additional information:
http://php.net/manual/en/function.setcookie.php
<script>
var refreshTime = 180000; // every 3 minutes in milliseconds
$(document).ready(function(){
setInterval(sessionCheck,refreshTime);
});
function sessionCheck() {
$.ajax({
cache: false,
type: "GET",
url: "refreshSession.php",// <?php session_start(); ?>
success: function(data) {
}
});
}
</script>

Categories