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>
Related
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.)
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
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"
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
How to set session lifetime in PHP? I Want to set it to forever as long as the request is exist. The request is AJAX. My PHP code that handle AJAX request is:
// AJAX.php
<?php
session_start();
$_SESSION['counter'] = $_SESSION['counter'] + 1;
header('Content-type: application/json');
echo json_encode(array('tick' => $_SESSION['counter']));
?>
and the JavaScript:
$(document).ready(function() {
function check() {
getJSON('ajax.php');
}
function getJSON(url) {
return $.getJSON(
url,
function(data) {
$("#ticker").html(data.tick);
}
);
}
setInterval(function() {
check();
}, 10000); // Tick every 10 seconds
});
The session always resets after 300 seconds.
The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.
For set the time life in php, you can use the function session_set_cookie_params, before the session_start:
session_set_cookie_params(3600,"/");
session_start();
For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.
But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.
You can have a Table "Sessions":
session_id int
session_hash varchar(20)
session_data text
And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:
On login:
setcookie('sessid', $sessionid, 604800); // One week or seven days
setcookie('sesshash', $sessionhash, 604800); // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function
If the user return:
if (isset($_COOKIE['sessid'])) {
if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
$_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
} else {
// Dont validate the hash, possible session falsification
}
}
Obviously, save all session/cookies calls, before sending data.
Set following php parameters to same value in seconds:
session.cookie_lifetime
session.gc_maxlifetime
in php.ini, .htaccess or for example with
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);
for a day.
Links:
http://www.php.net/manual/en/session.configuration.php
http://www.php.net/manual/en/function.ini-set.php
Prior to PHP 7, the session_start() function did not directly accept any configuration options. Now you can do it this way
<?php
// This sends a persistent cookie that lasts a day.
session_start([
'cookie_lifetime' => 86400,
]);
?>
Reference: https://php.net/manual/en/function.session-start.php#example-5976
Sessions can be configured in your php.ini file or in your .htaccess file. Have a look at the PHP session documentation.
What you basically want to do is look for the line session.cookie_lifetime in php.ini and make it's value is 0 so that the session cookie is valid until the browser is closed. If you can't edit that file, you could add php_value session.cookie_lifetime 0 to your .htaccess file.
Since most sessions are stored in a COOKIE (as per the above comments and solutions) it is important to make sure the COOKIE is flagged as a SECURE one (front C#):
myHttpOnlyCookie.HttpOnly = true;
and/or vie php.ini (default TRUE since php 5.3):
session.cookie_httponly = True
I dont see this mentioned anywhere, but setting ini_set('session.gc_maxlifetime', $max_lifetime); in the PHP file itself is usually not going to have the desired affect if the php.ini file has a LOWER value and the server hosts multiple domains/vhosts. If you have User on X website, and the maxlifetime is set to 10 seconds (not a real value, this is just for example) in the PHP file and then have the maxlifetime set to 5 in php.ini something interesting/unexpected will happen if you have multiple domains/vhosts.
When a 2nd user visits a site that HASNT set ini_set('session.gc_maxlifetime', $max_lifetime); in it's PHP file and it defaults to whatever php.ini has, that will cause PHP's garbage collection to fire using 5 seconds rather than 10 seconds as maxlifetime, thus deleting the user's session which was supposed to last at least 10 seconds.
Therefore, this setting should almost NEVER go in the PHP file itself and should actually be in the vhost entry if your setup has this capability and falls into this type of scenario. The only exception to this is if your server only hosts 1 website/vhost who's PHP files will always override whatever php.ini has.
This happens because all sites use the same tmp dir to store session data. Another mitigation solution would be to set the session tmp dir per vhost. And yet another (not recommended) solution is to simply disable session.cookie_lifetime completely in php.ini by setting it to 0.
As long as the User does not delete their cookies or close their browser, the session should stay in existence.