How to change the default session lifetime in Silex.
The default value is 30mn;
The doc http://silex.sensiolabs.org/doc/providers/session.html#usage is giving a clue but doesn't show an example how to do it.
When I set a session like this:
$app['session']->set('username', 'my username');
The session variable is set but it expires in 30mn.
Silex uses the Symfony Components. You can set the expiration using the migrate method for a certain session.
E.g.: $app['session']->migrate(false, 3600);
Docs
To set the expiration for all sessions:
$app['session.storage.options'] = [
'cookie_lifetime' => 3600
];
Source
Don't forget that you must have some coherence between lifetime settings in Silex and lifetime settings in your php.ini.
By default, PHP lifetime sessions are set to 1440 seconds. If you don't change this default value, the session garbage mecanism (run by /etc/cron.d/php5) will remove "old" sessions (i.e. sessions with 1440 seconds of inactivity).
Here is the explaination of /etc/cron.d/php5 :
# This purges session files in session.save_path older than X,
# where X is defined in seconds as the largest value of
# session.gc_maxlifetime from all your SAPI php.ini files
# or 24 minutes if not defined. The script triggers only
# when session.save_handler=files.
#
# WARNING: The scripts tries hard to honour all relevant
# session PHP options, but if you do something unusual
# you have to disable this script and take care of your
# sessions yourself.
Related
I have tried multiple way to extend this, so as to not have to log in every 1440 seconds on a development server. Yet the problem still persists.
Could anybody advise on the "correct" way to achieve this? I want to set to cookie session timeout to 3600 (1 hour) instead of the default 1440.
I have tried:
Set: 'session.gc_maxlifetime' within my php.ini file
Gone onto phpmyadmin under Settings => Features => General => Login cookie validity and set this to be the timing I want.
Gone into config.ini.php in the phpmyadmin files and set: '$cfg['LoginCookieValidity']' to the required time.
Each attempt I have made sure to restart apache so as to load the new configuration. However the problem still persists.
Any help/advise will be much appreciated.
You have to edit phpmyadmin's configuration file (config.inc.php) and set the variable $cfg['LoginCookieValidity'] = 3600, I've put it at the end of the file.
Next, you have to increase the php session timeout if it is lower than 3600 seconds, to do that you have to set session.gc_maxlifetime in the php.ini file.
After that you have to restart apache.
I have done it so and it works on Ubuntu 14.04.
First you need to verified that is ini_set allowed on your system or not?
To find out what the default (file-based-sessions) session timeout value on the server is you can view it through a ini_get command:
$currentTimeoutInSecs = ini_get(’session.gc_maxlifetime’);
// php.ini setting required for session timeout.
ini_set(’session.gc_maxlifetime’, 3600);
ini_set(‘session.gc_probability’,1);
ini_set(‘session.gc_divisor’,1);
session_set_cookie_params(3600);
session_start(); // ready to go!
if you want to change the session.cookie_lifetime.
This required in some common file because to get the session values in whole application we need to write session_start(); to each file then only will get $_SESSION global variable values.
$sessionCookieExpireTime=8*60*60;
session_set_cookie_params($sessionCookieExpireTime);
session_start();
My Symfony2 application displays a main page, and from there on it primarily uses AJAX requests to display content to the user via modals.
I've noticed that after the user is idle for some period of time (around 15-30 minutes) the session is destroyed, and the user is logged out and needs to log in again. This is incredibly frustrating, since I can't expect users to log in again every time they've been idle for a few minutes.
As far as I can tell, this problem should not be happening according to my config.yml file, which is as follows:
framework:
session:
cookie_lifetime: 0 # Session lifetime in seconds
gc_maxlifetime: 28800 # Seconds after which data will be seen
# as garbage and potentially cleaned up
handler_id: ~ # Current using the default session handler
For completeness, my current environment is as follows:
Symfony 2.4.8
PHP 5.4
Session handler: default (file-based according to php.ini)
Ubuntu Server 12.10
Summary:
What should be happening: users should not be logged out, even after being idle for hours
What is actually happening: users are being logged out after being idle for 15-30 minutes
How can I fix this?
The problem:
It turns out that on Debian / Ubuntu systems, there is a system cronjob which runs every 30 minutes, cleaning out all "old" sessions. Herein lies the problem.
The cronjob doesn't actually know what constitutes "old". The cronjob simply calls a PHP-CLI script located at /usr/lib/php5/maxlifetime which then removes all session files that exceed a certain age. Since the script is involved by PHP-CLI, and independently of Symfony2, it has no idea what values you specified for gc_maxlifetime and cookie_lifetime in your Symfony2 config file. Instead, if just defaults to using the session.cookie_lifetime and session.gc_maxlifetime values from the /etc/php5/cli/php.ini config file, which by default, is 24 minutes. So no matter what you specify in your Symfony2 config file, if you are idle for too long, your session will be removed.
The solution:
Either delete the cronjob file at /etc/cron.d/php5 or,
Store your sessions in a database where they can't be touched by the cronjob
I set remember me cookie set to default, and then in security.yml
security:
firewalls:
main:
form_login:
remember_me: true
remember_me:
key: mycookie
lifetime: 2592000 # 30 days
path: /
domain: ~
always_remember_me: true
My first answer seems not suitable for your issue. Maybe this one will help.
Do you clear Symfony cache between your requests ?
Extract of symfony documentation :
save_path
type: string default: %kernel.cache.dir%/sessions
This determines the argument to be passed to the save handler. If you
choose the default file handler, this is the path where the session
files are created. For more information, see Configuring the Directory
where Session Files are Saved.
You can also set this value to the save_path of your php.ini by setting the value to null.
By default, Symfony stores sessions in the cache directory that is emptied while clearing cache...
Extract of symfony documentation :
cookie_lifetime
type: integer default: null
This determines the lifetime of the session - in seconds. It will use
null by default, which means session.cookie_lifetime value from
php.ini will be used. Setting this value to 0 means the cookie is
valid for the length of the browser session.
So, 0 is not infinite session BUT browser session... You should define a big amoutn of seconds and test it.
Travis T, I went the simplest route of all. I said
nano /etc/cron.d/php5
This opened the file showing the tremendously long crontab code that purges your session by default every 30 mins. The script was preceded by a #, and all I did was uncomment both lines by removing the #. So:
# Look for and purge old sessions every 30 minutes
# 09, 39, * * * * root #[ -x /usr/lib/php5/maxlifetime ] && [ etc
it's a long file.....]
I just removed the 2 #'s in front of Look and 09. That's it !
I have some issues concerning the timeout of a php session. I have set the following values during runtime of the application:
session.gc_maxlifetime = 3600
session.cookie_lifetime = 3600
session.save_path = myApplicationPath/tmp
session.use_cookies = 1
session.use_only_cookies = 1
However, my session keeps expiring in about 30 mins. Also, my tmp directory remains empty, so it appears no cookies are actually being set. echoing ini_get("session.save_path") does return the right path though.
Note:
If different scripts have different values of session.gc_maxlifetime but share the same place for storing the session data then the script with the minimum value will be cleaning the data. In this case, use this directive together with session.save_path.
PHP Manual
I'd say that PHP cannot find your save_path or does not have permission to write on that, so it stores session files (not cookies) in the default shared directory (so the site with shortest gc_maxlifetime will remove sessions from all other sites).
This is really bugging me. Has been for years. No matter what I do with core.php or php.ini, my logins timeout after about an hour - usually. Some deployments of identical code and configuration timeout after a respectable amount of time.
This is what I have at the moment on one site - timed out after about an hour:
session.gc_divisor 1000
session.gc_maxlifetime 86400
session.gc_probability 1
Configure::write('Session.timeout', '28800');
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
And another - lasted all night:
session.gc_divisor 100
session.gc_maxlifetime 14400
session.gc_probability 0
Configure::write('Session.timeout', '315360000');
Configure::write('Session.checkAgent', false);
Configure::write('Security.level', 'medium');
Now, before you get excited and say, "Well, the answer is there in the Session.timeout value", let me tell you that this site usually times out after about twenty minutes!
Somewhere I read that on shared hosting, other applications can reset the session by clearing the php-defined session directory. This was alluded to by Rowlf in his answer.
CakePHP offers the option to configure the way sessions are handled. In core.php I changed this to 'cake' (by default it is 'php'):
/**
* The preferred session handling method. Valid values:
*
* 'php' Uses settings defined in your php.ini.
* 'cake' Saves session files in CakePHP's /tmp directory.
* 'database' Uses CakePHP's database sessions.
*/
Configure::write('Session.save', 'cake');
I also ensured that the session timeout and the corresponding php.ini values are the same:
/**
* Session time out time (in seconds).
* Actual value depends on 'Security.level' setting.
*/
Configure::write('Session.timeout', '86400');
So far, the system hasn't logged out.
I don't think this is a Cake-specific thing; I've seen it when no frameworks were involved - it's most likely an issue with your PHP config settings.
Things you should check/do to fix the issue:
Specify a dedicated path to store
sessions in session.save_path if you don't already do so.
Don't store them in /tmp - some other process may come along and wipe them
for you.
Make sure (and I mean really sure) that the value of session.gc_maxlifetime is what you think it is (86400 if you want your logins to time out after 24 hrs of inactivity, etc.). Same with session.gc_divisor and session.gc_probability. Even though the PHP Manual specifies that session settings can be set on any level, depending on the dodginess of your PHP build (they're all slightly buggy in their subtle ways :)) you may find they don't actually take effect unless set in the global php.ini file as opposed to in the code, .htaccess, etc. Just output them in your actual app to be sure they are applied.
Also, depending on your environment, check if the PHP CLI build is using the same php.ini file as the default PHP build - if the CLI build is using another config file and you have cron jobs using the CLI build, the cron job scripts could be invoking the session cleanup procedure.
If you have many CakePHP apps on the same server, this can be the cause of you troubles. Don't forget to :
Prefix each app differently ($prefix on core.php).
Change the name of each cookie path :
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 4320,
'ini' => array(
'session.cookie_path' => '/name_app', // this for each app
)));
If I hit a page which calls session_start(), how long would I have to wait before I get a new session ID when I refresh the page?
Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.
I believe the default is 1440 seconds (24 mins)
http://www.php.net/manual/en/session.configuration.php
Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:
How do I expire a PHP session after 30 minutes?
The default in the php.ini for the session.gc_maxlifetime directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:
http://www.php.net/manual/en/session.configuration.php
You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:
php_value session.gc_maxlifetime "3600"
Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.
The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.
it depends on your php settings...
use phpinfo() and take a look at the session chapter. There are values like session.gc_maxlifetime and session.cache_expire and session.cookie_lifetime which affects the sessions lifetime
EDIT:
it's like Martin write before
According to a user on PHP.net site, his efforts to keep session alive failed, so he had to make a workaround.
<?php
$Lifetime = 3600;
$separator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN")) ? "\\" : "/";
$DirectoryPath = dirname(__FILE__) . "{$separator}SessionData";
//in Wamp for Windows the result for $DirectoryPath
//would be C:\wamp\www\your_site\SessionData
is_dir($DirectoryPath) or mkdir($DirectoryPath, 0777);
if (ini_get("session.use_trans_sid") == true) {
ini_set("url_rewriter.tags", "");
ini_set("session.use_trans_sid", false);
}
ini_set("session.gc_maxlifetime", $Lifetime);
ini_set("session.gc_divisor", "1");
ini_set("session.gc_probability", "1");
ini_set("session.cookie_lifetime", "0");
ini_set("session.save_path", $DirectoryPath);
session_start();
?>
In SessionData folder it will be stored text files for holding session information, each file would be have a name similar to "sess_a_big_hash_here".
You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60 too.
But watch out, on most xampp/ampp/...-setups and some linux destributions it's 0, which means the file will never get deleted until you do it within your script (or dirty via shell)
PHP.INI:
; Lifetime in seconds of cookie or, if 0, until browser is restarted.
; http://php.net/session.cookie-lifetime
session.cookie_lifetime = 0