Check if Codeigniter session has expired with AJAX - php

I'm creating a Helpdesk system, sometimes a user get more than two hours without using the system and then return when the session has expired, but the last loaded page remains on the screen (a form, for example) and the user can use it normally, but when he submits the form he is redirected to the login page (it's ok), but the user loses data entered.
I want to create an AJAX function that checks if the session has expired or not. That function should be performed using setTimeout() or setInterval().
I've tried using the "sess_expiration" but it seems that this value does not reset on page load, i.e. after ending the appointed time (7200 by default) it forces the session expiration.

You can do it like this
$.ajax({
type : 'POST',
url : '<?php echo site_url('controllername/methodname')?>'
success : function(data){
if(data){
//session available
}else{
// expired
}
});
And controller method
function methodname(){
$user_id = $this->session->userdata('user_id');
if($user_id){
echo 1;
}else{
echo 0;
}
}
You can wrap ajax request in function and return the result everytime with TRUE or FALSE. Moreover setInterval can call this function for checking session.

Codeigniter session class has method which let us know about session expiry.
function your_method(){
$this->session->sess_read() === false ? echo "0" : echo "1";
}

Related

Redirect the user if the $_SESSION has expired in PHP

On each page I check if the user is connected (i.e.: if the user session is active or not).
validateSession();
function validateSession() {
if (!isset($_SESSION['CurrentLogged_USR_Id'])) {
header("Location: 'http://example.com');
}
}
It's working.
But if the user is on a page from a long time and the system needs to make an ajax call, the same check is done but do not redirect the user.
Why ?
I've include the validateSession() on my php page called by ajax but the redirection is not make.
Thanks.
You cannot redirect in PHP that is called through AJAX. Rather return a flag that identifies that session has expired and make redirection in JavaScript.
Below is sample code snippet.
$.ajax({
url: "urlToAJAX.php",
success: function(isSessionExpired){
if(isSessionExpired)
{
window.location = "http://example.com";
}
}});
You can follow this code.
Ajax
$.ajax({
url:..
type:..
success(data){
if(data == "SESSION_EXPIRED"){
window.location = "your-login-page";
}
}
});
In your PHP code, you have check if the session is available. If not echo the string SESSION_EXPIRED.

Index page refresh when logged-in

I have an index.php page, which behaves as follows :
if a session var exists and is set, it displays a menu + some info
about the user (userID, IP adress, link to disconnect)
if the session var is not set, it displays a login form
So if you go there for the first time, you'll see the login form.
When the user provides his login+password, there is an AJAX call to login_check.php. The main purpose of this page is to generate a session variable (if the user info meets several requirements), but it also sends error messages back to the bottom of the form (under the form of JSON var) in case of authentification failure.
Here is its core :
login_check.php
if (authentification($login, $password)) {
//creates the session variable
$_SESSION['auth'] = $login;
//? here I'd like to refresh the index page
}
else {
//the error that will be displayed at the bottom of the form
$json_err .= "Incorrect login or password";
}
index.php looks like this :
if (isset($_SESSION['auth'])) {
//the menu is displayed, because the user is looged-in
}
else {
//the login form is displayed, because the user is not authentificated
}
So far, I have to manually refresh the index page so that it takes the session var into account. Is there a way to do it automatically ?
Solutions like "location.reload" are not really suitable, because of the error messages that might be displayed. I also tried to call again index.php from login_check.php using "include" or "header" but it didn't work.
Should I make a conditional refresh within my jQuery function, depending on what data was sent back by login_check.php ?
What would you advice ?
Thanks
I think you need to eun your checklogged.php for example once every 5 min and if user if not logged redirect to login page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$status = $('#islogged').load('login_check.php');
setTimeout("getStatus()",50000);
}
</script>

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.

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?

Categories