Increase Session Time Out in PHP website on SHARED HOSTING - php

I have already tried all the possible solutions from the Stack Overflow. But none of them are working.
I recently got to know about that in Shared Hosting we have a different way of doing that. If anyone could help me in detail about how to do it so that session stay active for at least 24 hours.
ini_set('session.gc_maxlifetime', 86400);
This does not solve my problem before the session start call.

I m not sure if this solution is for you but i will post how i did.
I do logout my user after XX minutes but to keep live session i call file with ajax and reset the sessions. If my set time expire i destroy session. This of course will only work if page is still opened.
In header i set:
if(!empty($_SESSION['afkTime'])){
unset($_SESSION['afkTime']);
}
In <head></head> tags i check how log time user is inactive:
<script>
var refreshSn = function ()
{
var time = 1200000; // 20 mins | 1min = 60000 miliseconds
setTimeout(
function ()
{
$.ajax({
url: 'refresh_session.php',
cache: false,
success: function (data) { refreshSn(); console.log(data); if(data=='AFK logout'){ location.reload(); } }
});
},
time
);
};
// Call in page
refreshSn()
</script>
In refresh_session.php if AFK time is bigger than my set time and if so i logout:
<?
session_start();
if(empty($_SESSION['afkTime'])){
$_SESSION['afkTime'] = 1200000;
$_SESSION['login_user'] = $_SESSION['login_user']; //REWRITE SESSION TO KEEP IT
$_SESSION['session_id'] = $_SESSION['session_id']; //REWRITE SESSION TO KEEP IT
echo 'AFK started';
die();
}else{
if(!empty($_SESSION['afkTime']) && $_SESSION['afkTime']>= 7200000){
unset($_SESSION);
session_destroy();
echo 'AFK logout';
die();
}else{
$_SESSION['afkTime'] = $_SESSION['afkTime']+1200000;
$_SESSION['login_user'] = $_SESSION['login_user']; //REWRITE SESSION TO KEEP IT
$_SESSION['session_id'] = $_SESSION['session_id']; //REWRITE SESSION TO KEEP IT
echo 'AFK '.$_SESSION['afkTime'];
die();
}
}

Check what the session.save_path is set to.
If that is just a global temp directory you share with all other users running their sites on this machine - then the garbage collection triggered by them, with their much lower settings, might wipe your session data files as well.
In that case, you should change this setting to use your own directory. (That directory should of course not be publicly available via HTTP.)

Related

How to Force log out php session after x minutes (not inactive log out)

The below code expires a page only on manual page refresh. I want the page to automatically expire the session and log out the user and redirect to the login page.
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || (time() - $_SESSION['login_time']) > 60) /*session expires after 1 minute*/
{
//logout code such as session unset, destroy;
header("Location:login.php");
}
else
{
//page contents if any
}
?>
gc_maxlifetime has it's own issues. So I don't want to implement it. Found another using ajax with php, but want to make sure is there any other possible. please confirm a way to implement this.
Normally, PHP only executes in response to HTTP requests, and therefore sessions are not cleaned until a request arrives. When and how this is done is configured using the session configuration parameters.
While you cannot directly run the session management code, you can cause it to run by configuring the parameters and then simulating a request via cron or a similar tool. Ping your server every minute (or whatever) with an unpublished URL request that sets session.gc_probability to 100 and then starts a session. This will cause the session management code to garbage collect the sessions--which will effectively cleanup any timed out sessions.
You can determine the time of the session with session_cache_expire(minutes);
<?php
session_cache_expire(30);
session_start();
More info: http://php.net/manual/en/function.session-cache-expire.php
You can do like this with jQuery.ajax or another ajax you like:
<?php
$sessiontime = 60; // 1 minute
$time = $_SESSION['login_time']-time()+$sessiontime;
?>
<script>
setTimeout(function() {
$.ajax({
url: '/path/to/logout-file.php',
dataType: 'json',
complete: function(){
window.location.href = 'login.php';
}
});
}, (<?=$time?>*1000));
</script>
you can use meta refresh
eg 30 minutes
META HTTP-EQUIV="refresh" content="1800;URL=../logout.php"

How to check system is idle or not in php?

I am developing a project management system. I am trying to track working time of a user. The time tracking page contains a timer and the user start tracking before they start their work.
Its working perfectly but in the case of system shut down or idle the time tracker doesn't stop. How can I check the system (Not the browser window or tab) is idle or not?And I want to show a confirmation message if browser tab is closed.I am use the code
$( [window, document] .on( 'beforeunload ', function () {
//alert
});
But "beforeunload" can't return any value.How to return a true or false value in beforeunload function in javascript
Tracking system would not be a safer side so detecting window/tab close is your best option.
Set a 'time' flag as session data, and check if the session is still 'new/not exceeding a certian limit' to keep them logged in(or your functionality) each pageload.
//on pageload
session_start();
$idletime=60;//after 60 seconds the user gets logged out
if (time()-$_SESSION['timestamp']>$idletime){
session_destroy();
session_unset();
}else{
$_SESSION['timestamp']=time();
}
//on session creation
$_SESSION['timestamp']=time();
Another Option:
<?php
/* set the cache limiter to 'private' */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
/* set the cache expire to 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();
/* start the session */
session_start();
echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>
Reference: session-cache-expire

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

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>

Logging out after certain amount of time

What would the best way be to logout a user from a PHP application (so basically just perform a redirect) after X seconds of inactivity? For "inactivity" I'd count the time of the last page load, and if the current time is more than X seconds away, perform the redirect.
Is this something that would need to be achieved with Javascript?
You can use just html meta tag:
<meta http-equiv="refresh" content="1000;url=buy.aspx">
put it in head
where 1000 is a time in sec and url is an url to redirect.
Just answered this question yesterday... the OP wanted to ask after certain amount of time, it the user would like to stay logged in or not.
For a plain redirect without any confirmation, you can use a simple setTimeout call:
var minutes = 30;
setTimeout(function(){location.href = 'logout.php';}, minutes*60*1000);
Do you really want a redirect for some reason?
Usually each user session has an associated timestamp. You then make sure the session hasn't expired for the user, or ask them to log in. So in effect, you're just making sure sessions are valid.
If you redirect someone to a logout page, you really are not achieving anything. You will also need to make sure the session has not timed out server side. Anything that is client side, including redirects to a logout page, is unreliable, and can be circumvented.
The simplest form in PHP:
<?php
session_start();
$session_lifetime = 60*60; // 1 hour
if (!isset($_SESSION['time']) || !$_SESSION['time']) {
$_SESSION['time'] = time();
}
if (time() - $_SESSION['time'] > $session_lifetime) {
// session has expired
$_SESSION['user'] = null;
$_SESSION['time'] = null;
} else {
// keep session alive
$_SESSION['time'] = time();
}
What if the user starts typing in the form on the page and hasn't finished by your time out period? I handle inactivity in another way than described in other answers so far.
var rowLockSeconds = 0;
function startRowLockTimer()
{
setInterval("incrementRowLockTimer()",60000);
$("input").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; });
$("textarea").keypress(function (e) { rowLockSeconds=0; }).click( function() { rowLockSeconds=0; ; });
window.onbeforeunload = function obul() { if (hasChanged) { return 'You will lose any unsaved changes you\'ve made.'; } }
window.onunload = clearRowLock;
}
So as they've logged in, the row lock timer starts at 0. Every 60 seconds it calls the interval function to see if it has timed out.
function incrementRowLockTimer()
{
rowLockSeconds = rowLockSeconds+60;
// 10 minute timer to clear someone out of a page if there has been no activity
if (rowLockSeconds >= 600)
{
window.onbeforeunload=null;
// clear rowLock with request here
$.get('../ajax/rowLock-server.php?do=delete&rowLockID='+currentRowLockID+'&userUUID='+currentUserUUID, function() {
alert('You have been logged out of this page after 10 minutes of inactivity.');
document.location.href='../main.php';
});
}
}
The AJAX controls clear out the DB row lock.
The key is the input and textarea bindings so that if the user types anything into the form, the timeout is reset and they have another 10 minutes.

Categories