Handling redirection when session timeout via ajax - php

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.

Related

Losing session after a javascript redirect

I have a html file basically calls a php file via ajax and if a login is successful, redirects the user to the index.php page via a redirect (window.location... etc.)
When the index.php loads it checks to see if a session variable is set and if not - redirects the user back to the login page. The problem is that even though the login is a success and the session variable has been set, it is no longer set when the index.php file is loaded. Please see image for overview of process.
The problem is that even though the login is successful and the $_SESSION variable was successfully set, after the javascript redirect the session is reported as being not set.
I do include the session_start() directive in both php files. Any advice would be much appreciated.
Sorry for not including code - here is the code I am using 1st - the ajax request and redirect from html page
function loginCompany(){
let email = 'test#test.com';
let pass ='124';
if ((email =='') || (pass==''))
{
alert('Please enter a user name or email and password');
$('#email').focus();
return;
}
$.ajax({
url: 'compAuth.php',
type: "POST",
async:true,
dataType: 'json',
data: {
email:email,
pass: pass,
userName : email
},
success: function (res) {
if (res){
if (res.status == 'Success')
{
window.location.replace('index.php');
return;
}
else {
console.log('not success : ');
if (res.status == 'Error') {
alert(res.description);
}
}
}
},// Success
error: function (res) {
}
});
}
Next is a snippet from Page B (the php script that sets the session and returns json results
$response = [ 'status' => 'Success'];
session_start();
$_SESSION['dbname'] = $row['dbname'];
echo json_encode($response);
And lastly - Page C which is called after a redirect from the initial HTML page (page A)
session_start();
if (!isset($_SESSION['dbname'])) {
header("location: login.php");
So its this last page (page C the index,php file) that does not see the $_SESSION variable as being set
Many thanks..
Paul.
P.S Also just to say that there is no cross-domain traffic - its all on the same domain :) Thanks.
After a couple of hours of destructive testing, it seems that the problem was with one of my required php files. It seems there was an error in one of the files but instead of generating an error - it just stopped the session variable from being set. Does not seem logical but at this point - I am just happy its working. I am new to this and assumed I was just "getting it wrong". Sorry for wasting peoples time and thanks for the feedback.
Paul.

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...

Prevent PHP SESSION expiration using AJAX

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

Call ajax to clear session after user has left page

I want to clear the php session array every time a user leaves my page, but my page has links with query strings. I don't want to clear the session array, when a user clicks on a link with a query string. I have tried the following javascript code but it does not work when the user leaves the page.
somepage.php
var url = new RegExp(/somepage.php\?sort=.*/);
if (url.test(document.location.href)){
//do nothing
}
else {
$(window).unload(function(){
$.ajax({
url: 'clear_session.php'
});
});
}
Calling a webserivce onunload is very unrealiable. Why not just unset the PHPSESSID cookie? This wont clean up the session on the server, but it will give the user a new empty session when he visits again.

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?

Categories