My default PHP session is 30 minutes.
I got this first code :
<?php
session_set_cookie_params(28800);
session_name('TEST');
session_start();
session_regenerate_id(true);
$_SESSION['test'] = 'jam';
?>
And this second one :
<?php
session_set_cookie_params(28800);
session_name('TEST');
session_start();
session_regenerate_id(true);
echo $_SESSION['test'];
?>
The fact is, my session is lost after 30 minutes without activity.
Timed example :
00:00 : run first script
00:10 : run seconde script : i got "jam"
00:20 : run seconde script : i got "jam"
00:40 : run seconde script : i got "jam"
01:11 : run seconde script : session is lost
Hope you can give me any clue to fix this.
Take a look at this answer at session_set_cookie_params() page in PHP Manual, and see if that helps you!
Cookie lifetime is only one part of the equation. The server-side session storage is the other. Make sure that session.gc_maxlifetime is set high enough as well.
You are only setting the lifetime of the cookie, that has nothing to do with the actual lifetime of the session data. If you're using the default session save handler that saves sessions to the filesystem, the lifetime of the session data is controlled by session.gc_maxlifetime directive. You can override this value with ini_set like this:
ini_set('session.gc_maxlifetime', 28800);
Do note that if you also have other scripts that use sessions and they share the same save path for sessions, then the minimum gc_maxlifetime is used for all sessions in that directory. Hence if you want to change the gc_maxlifetime value, that usually means you also want to specify your own path where the sessions are stored. You can do so with the session_save_path function:
session_save_path('/path/to/your/sessions');
Related
I created a folder on the root of my website where session data is stored outside of the public_html. I did this to make the sessions on my website last longer because I was having a problem where they would time out after 30 minutes. I tried many ways to fix it but nothing worked until I tried the code below. I'm using the following code to create sessions that last a day, and the code stopped the problem of them timing out after 30 minutes:
ini_set('session.save_path', '/home/server/.sessionsData');
ini_set('session.gc_maxlifetime', 86400);
ini_set('session.cookie_lifetime', 86400);
ini_set('session.cache_expire', 86400);
ini_set('session.name', 'website');
session_start(); // Session ready to go!
After making this change, the sessions don't time out after 30 minutes anymore, but I have a new problem where my "logout code" which destroys the sessions is no longer ending the sessions like it used to.The following code is what I'm using to logout and destroy sessions, but it no longer works like it used to:
session_start();
session_destroy();
header("location: https://website.com");
What should I do to make it so that the sessions are destroyed and the corresponding session data that is stored my '/home/server/.sessionsData' folder gets deleted? If I go into the folder and delete the session data file directly, it ends the session in the user's browser.
Thanks in advance for looking into this.
As mentioned in comments
Perhaps your ini_set() code, or at least the path changing part, needs to be in your log out script as well.
In code form:
ini_set('session.save_path', '/home/server/.sessionsData');
session_start();
session_destroy();
header("location: https://website.com");
Using session_unset along with session_destroy, is an effective means of actually clearing out SESSION data.
session_start();
session_unset(); //--> frees all session variables currently registered.
session_destroy(); //--> destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
I have also read on PHP manual comments the following can help in stubborn browsers:
session_write_close(); //--> End the current session and store session data.
setcookie(session_name(),'',0,'/');
session_regenerate_id(true); //--> replace the current session id with a new one, and keep the current session information.
I'm using a java based uploading construct http://www.javaatwork.com/java-upload-applet/details.html that I tried running over night.
It basically stores everything on the server's hard drive (/var/www/private/$userId)
Makes sure that data is well-formed
Then passes it onto a permanent storage (Amazon S3).
After step 1 completes, I run the following code:
if($_SESSION['userId'])
{//Makes sure that data is well-formed}
else
{echo 'you are not logged in';}
I tried running this for four hours only to find you are not logged in printed to the screen.
Here are the appropriate directives in the cgi php.ini file (I'm using ubuntu 12.04 with apache2.)
session.gc_probability = 0
session.gc_divisor = 1000
session.gc_maxlifetime = 14400 //this is 30 hours, which is far greater than the 4 hours it was running
session.cache_expire = 1800
session.cookie_lifetime = 0
Most of these directives are the default with exception to session.gc_probability and session.gc_maxlifetime.
I was trying to resolve this issue and came across a really helpful blog by Jeff from which I inferred that browsers can cause the PHPSESSID cookie stored in the browser to be deleted if a period of inactivity on the website from within the browser occurs. He suggests
"Create a background JavaScript process in the browser that sends regular heartbeats to the server. Regenerate a new cookie with timed expiration, say, every 5 or 10 minutes."
http://www.codinghorror.com/blog/2008/04/your-session-has-timed-out.html
So I decided to do just that.
function myTimeoutFunction()
{
$.ajax({
url: "heartbeat.php",
success: function() {
}
});
setTimeout(myTimeoutFunction, 15*60*1000);
}
myTimeoutFunction();
heartbeat.php
<?php session_start(); ?>
I'm about to test this for an upload that should take ~4 hours. However I just read the following
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called)
https://stackoverflow.com/a/1516338/784637
If I had 3 session variables, $_SESSION['userId'] $_SESSION['firstName'] $_SESSION['lastName'], would I need to reset all their values in heartbeat.php
session_start();
$_SESSION['userId'] = $_SESSION['userId'];
$_SESSION['firstName'] = $_SESSION['firstName'];
$_SESSION['lastName'] = $_SESSION['lastName'];
Or could I just reset one value
session_start();
$_SESSION['lastHeartbeat'] = time();
so that the other three would not expire?
The PHP session is kept as a whole; any changes in $_SESSION will update the change time and, by extensions, preserve the entire session.
Concerning the actual issue: PHP shouldn't GC sessions until the max time is reached, but that doesn't mean PHP is always clearing it. By default, sessions are kept in the /tmp (or another) directory and some Linux distros will have cron jobs that may clean the folder out from time to tome. Check for crons or other things that may clear the sessions independent of PHP too.
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.
I was working in a project where another developer wrote the code,while a user is login the session_start() as usual and then he is cheking like belows:
if($a['userName'] == $username && $a['password'] == $pwd)
{
$_SESSION['id'] = $a['id']; ?> <script language="javascript"type="text/javascript">window.location="host.php";</script> } else {
$msg= "Invalid Username Password";
}
And when a user want to use the form after couple of seconds its logout and user can not submit data.
I have tried increasing session life time duration:
$sessionCookieExpireTime=8*60*60;
session_set_cookie_params($sessionCookieExpireTime);
And also tried with increasing session lifetime in runtime like below:
ini_set('session.gc_maxlifetime', '3600');
And finally tried by increasing php.ini session lifetime .
Unfortunately those did not work.
One thing I should mention that,there is no session_destroy() for logout issues.
Thanks in advance.
What kind of server are you working on?
On a shared server that runs multiple sites that use a shared session directory the session.gc_maxlifetime is in effect the shortest lifetime of all sites accessing that shared directory.
If the problem is on a development server, find out where the session files are stored and look at what happens to them.
It is also possible that the directory where the sessions are stored is not writeable. In that case the session variable is never stored in the first place.
In all three cases: try to store the session files in a different directory. In code you have to set the session directory with session_save_path() before you call session_start().
The timeout occurs when user idle activity for certain time. There is no way to logout automatically unless using session_destroy.
It may be possible that your code
$a['id'];
returns null by chance.
Also, you need to checkout which page is getting logged out.
Giving the full code may be easy to identify the issue.
I'd like to set the PHP session lifetime as long as possible util the browser is closed. Is it possible to implement this just by settings something in PHP script? Or do I have to change anything in PHP.ini configuration file?
PHP's default session setting is to make the session cookies... session cookies. They'll last for the lifetime of the browser and get deleted when it's closed/quit/exited. The relevant .ini setting is session.cookie_lifetime
I just went through this myself recently.
Here is the website I used:
http://www.captain.at/howto-php-sessions.php
Pay attention to the "session.php" section at the bottom.
before any output;
<?
session_set_cookie_params(0);
session_start();
/* Set to 0 if you want the session
cookie to be set until the user closes
the browser. Use time() + seconds
otherwise. */
?>