How to set lifetime of session - php

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.

Related

PHP Session Cookie not being sent to server

I am having problems with the buildin session functionality of php.
When I start the session the client recieves the session cookie as it is supposed to. But the cookie never gets send back to the server.
All other cookies get send (checked that multiple times). The host is correct and the path aswell.
The php.ini file seemed correct.
I also tried renaming the session cookie without success!
I want to add that every time I access the site I get another session cookie.
Also when I debugged this I added this line error_log(print_r($_COOKIE, true)); as the first line of my code. Still no session cookie.
Here is some code I'm using:
// This function exists so that I only start the session once.
function start_session() {
if(session_id() == "") {
session_start();
setcookie(session_name(), session_id(), time() + ini_get("session.cookie_lifetime"));
// The client gets this cookie!
}
}
start_session();
session.cookie_lifetime in my php.ini is 0. Might this be the cause?
I have no idea what might causing this.
The cause is time() + ini_get("session.cookie_lifetime") with session.cookie_lifetime being 0. Meaning the cookie will expire immediately.
Setting the session.cookie_lifetime to something like 3600 worked.

PHP Session variables null after about 30 minutes

I'm having an issue with session variables becoming null after about 35-40 minutes. However, the session ID appears to still show as valid (and the same number as it was before).
I've created some testing code which reads and displays the session variables and then reloads the page after an increasing number of seconds. It works until it gets to 2400 seconds, at which point the variables are null on next display. In other words, it's always null when it waits 2400 seconds between refresh. I've set the session.gc_maxlifetime in .htaccess to 7800 (and it's apparently set because it reads as 7800 with ini_get).
I'm either missing something obvious or some serious strangeness is at work here. This is driving me nuts.
This is on a Linux VPS with WHM.
Code to create the test session:
<?php
// start session
session_start();
// set session value
$_SESSION["session_memberid"] = 1234567;
$_SESSION["session_refresh"] = 2000;
// write file, close
session_write_close();
// display confirmation
echo json_encode(array(
'$_SESSION["session_memberid"]' => $_SESSION["session_memberid"],
'session_id' => session_id(),
'maxlifetime' => ini_get('session.gc_maxlifetime')
));
?>
Code to read the session (is reloaded automatically):
<?php
// start session
session_start();
// get session id
$session_id = session_id();
// get stored memberid
$member_id = $_SESSION['session_memberid'];
$_SESSION['session_memberid'] = $member_id;
// get last activity
$lastactivity = $_SESSION["last_activity"];
// increasing refresh time
$refresh = $_SESSION["session_refresh"];
$_SESSION["session_refresh"] = $refresh + 100;
// update time
$_SESSION["last_activity"] = time();
// write file, close
session_write_close();
...
(code to display and refresh variables)
Output when valid read:
{"memberid":1234567,"session_id":"c9d20d4992f184f29b259ef5ccab275f","sessionpath":"\/tmp","maxlifetime":"7800","sessioncookiepath":"\/","sessioncookielifetime":"0","referrer":"","autostart":"0","cache":false,"time":1365004882,"cookie":{"lifetime":0,"path":"\/","domain":"","secure":false,"httponly":false},"refresh":2400}
Output when invalid read shows memberid (the variable that we need), time (last_activity) and refresh time as null.
Any ideas?
Is it possible that the apache user doesn't have permissions to write in the /tmp directory, and the session is only active in ram for that time period. Once expunged out of ram, it would default to the file, which never got written to because of permissions?
As it turns out, the issue was that php.ini wasn't correctly being overridden by settings in .htaccess or ini_set at runtime, even though ini_get showed the value as overridden. The reason isn't clear but the working fix has been to simply change the session.gc_maxlifetime in the php.ini.

What is the best way to make "remember me" under php when using native sessions?

Previously i was creating additional cookie "rememberme" with unique hash, that was stored in the database, mapped to the user id.
If user had such cookie - website tried to find it's value in database, and if it was found session was setting up.
Later, developing new project i thought that it is maybe not very secure to generate this unique hash by myself, and keeping two cookies (native "PHPSESSID" + my "rememberme") for one operation (user identification) is overkill.
Maybe there is a way to setup not global session lifetime, but to setup it individually for different user sessions... or maybe it is better to keep user sessions in the database, mapped to the userid?
UPDATE 1
I thought if it is so hard to make "remember me" button, we can go another way - to make "Not my computer button". Idea is to set default cookie_lifetime for a week in php.ini (for example), and if user checkes this checkbox - we will set cookie_lifetime into zero using session_set_cookie_params function.
So, 1st question is - will session_set_cookie_params affect other users cookies (in documentation it is said, that session_set_cookie_params options will have effect until php process will be executing)
2d question is that if session_set_cookie_params is not affecting global settings, will session regeneration affect users, that don't want to keep a long-life cookie?
UPDATE 2: [Question 1 answer]
Just tested session_set_cookie_params function.
I wrote a script, that sets session cookie lifetime into zero using session_set_cookie_params and then executing for 30 seconds:
if ($_GET['test']) {
session_set_cookie_params (0);
while (true) {
sleep(1);
}
}
session_start();
So, in first browser i just started this script with ?test=1 parameter, just after that (while this script was executing) i started this script without parameters in the second browser. The answer is no - second browser's cookie was not affected. It had lifetime, that was specified in php.ini
UPDATE 3: [Question 2 answer]
Then, i've tried to check if regeneration affects session cookie lifetime, that was set by session_set_cookie_params.
Yes, it affects. If i set session cookie with customized lifetime, that was set by session_set_cookie_params, and then call session_regenerate_id(), cookie will have lifetime, set in php.ini
But, if we set session_set_cookie_params (0) before calling session_regenerate_id(), our cookie will have correct lifetime.
So, that's it! That was easy! 8)
Thank you, ladies and gentlemen!
If you want to do this only using sessions you can do the following if the user wants to be remembered:
if((isset($_POST['remember_me']) && $_POST['remember_me']) || ($_COOKIE['remember_me']) && $_COOKIE['remember_me'])) {
// store these cookies in an other directory to make sure they don't
// get deleted by the garbage collector when starting a "non-remeber-me"-session
$remember_me_dir = ini_get('session.save_path') . DS . "remember_me_sessions";
// create the directory if it doesn't exist
if (!is_dir($remember_me_dir)) {
mkdir($remember_me_dir);
}
// set the php.ini-directive (temporarily)
ini_set('session.save_path', $remember_me_dir);
// define lifetime of the cookie on client side
$expire_cookie = 60 * 60 * 24 * 30; // in seconds
session_set_cookie_params($expire_cookie);
// lifetime of the cookie on server side
// session file gets deleted after this timespan
// add a few seconds to make sure the browser deletes
// the cookie first.
$garbage_in = $expire_cookie + 600; // in seconds
// set the php-ini directive for the garbage collector of the session files.
ini_set('session.gc_maxlifetime', $garbage_in);
// send an additional cookie to keep track of the users
// which checked the 'remember_me' checkbox
setcookie('remember_me', 1, time() + $expire_cookie);
}
// now we are ready to start the session
// For all the users which didn't choose to check the 'remember_me' box
// the default settings in php.ini are used.
session_start();
Here you can read more about the session related php.ini-directives
As it was so hard to make "remember me" checkbox functionality, i came to another way, using only one cookie.
PREPARATION
1) I've prepared a form with three inputs:
"login" input [type=text]: user's login
"password" input [type=password]: user's password
"not my computer" input [type=checkbox]: that will tell us to use session cookie with lifetime = 0 (cookie must be deleted when browser will be closed)
2) I've set session.cookie_lifetime = 100500 to keep long-life cookies by default.
COOKIE SETUP
So, after user submits the form, we check - if he has selected to use short sessions - we call session_set_cookie_params(0) before setting session cookie to him (before actually using session_start()).
COOKIE REGENERATION
Then, when we need to regenerate session cookie, we can also do this easily with session_regenerate_id() function.
But we need to remember, that this function will re-set session cookie lifetime from php.ini by default.
So, we need also to call session_set_cookie_params() before regenerating a cookie.
BTW, You can store custom session cookie lifetime in $_SESSION.
It will look like this:
// Form handling, session setup
if ($_POST['not-my-computer']) {
session_set_cookie_params(0);
session_start();
$_SESSION['expires'] = 0;
}
// Session regeneration
if (isset($_SESSION['expires'])) {
session_set_cookie_params(0);
session_regenerate_id();
}
Details for this answer (and more deep explanations) you can find in the question text (while i was testing, i added answers/tests results there)

Does session.gc_maxlifetime specify the maximum lifetime since the last change of a single session variable?

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 destroy the session if the application is exceeding more than its given idel time using php

in my program for a security purpose it is neccessary to destroy the session variable if the application exceed more than its idle time.For This i am using this code,
// set timeout period in seconds
$inactive = 300;
// check to see if
$_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
$session_life = time() -
$_SESSION['start']; if($session_life
$inactive)
{ session_destroy(); header("Location: logout.php"); } }
$_SESSION['timeout'] = time();
But this code refresh the session variable every 5 min, i want to know how to destroy the session variable if the system is in the idle time. And also please tell me it create any other problem if i destroy the session variable . Thanks in advance
session_unset
#Edit:
Since the session data are considered garbage after the session timed out, no action should be needed really. It should be sufficient, to make sure, the garbage is cleared in a regular manner. So simply calling a page which creates a dummy session (once a minute fe.) should be enough. The garbage collector frequency may also be configured in php.ini.
However, you can verify this easily by monitoring your sessions (in file / database / memory).
Try this:
Edit php.ini - set session.cookie_lifetime with the intended value in seconds (300 seconds for your 5 minutes).
Restart your apache server.
Login
Test the session variable after 5 minutes (should have expired).
Remember, from the docs:
The default "0" value means that the cookie stays alive until the browser is closed. This is also the default value, if not set in php.ini.
So, you must set it: it defaults to zero - so it will never expire unless someone closes the browser window.

Categories