I am using PHP to create a website and I use session for some parts such as keeping user logged in, etc. I set the session timeout to zero, so it expires when the browser is closed.
My problem is that when the webpage is opened in the browser for some time and I don't use it, the session expires!
I mean when I'm not using the browser (eg. I'm editing my code, or I'm gone for lunch, etc) and after some time I go back to it and refresh it, some times it needs me to login again.
This is the method I use to start the session:
function StartSecureSession(bool $RememberMe = false) {
session_set_cookie_params(($RememberMe? 7*24*60*60 : 0), "/");
session_start();
session_regenerate_id(true);
}
Could anyone tell me what's happening?
Thank you
Note: I don't know if it matters, but I use Ubuntu 14.04 and chromium browser
Use to set session maxtime:
use following code in your confiuguration file:
// each client should remember their session id for EXACTLY 10 hour
ini_set('session.gc_maxlifetime', 36000);
session_set_cookie_params(36000);
Write this lines before session_start();
Or you can set it in your php.ini file too.
Related
I have a login page/system which has worked correctly for years, leaving the user logged in until he/she either closes the browser window or logs out manually. But lately (starting yesterday) after only a few minutes of inactivity the session cookie/s seems to expire, causing the user to be logged out automatically.
This happens on different browsers and different operating systems, the PHP version is 5.6.29, which has been changed recently (before it was 5.5 and even 5.3).
I create and refresh the session on every page with session_start(). The login script first checks user name and PW and also gets some other user data from the database. These other data are first saved in variables and then written into session variables like
$_SESSION['username'] = $name;
$_SESSION['usertype'] = $type;
The successful login state is saved like this:
$_SESSION['login'] = "ok";
On the other pages I check the login state like this:
session_start();
if(($_SESSION['login'] != "ok") OR ($_SESSION['usertype'] != "xxx")) {
header("Location: ../login.php"); /* redirects to login page if conditions are not true */
exit;
}
The login works, and logged-in users can proceed to other pages as long as the do it more or less in constant succession, but if someone waits a few minutes before proceding (i.e. without any acitivity), he/she is logged out (i.e. redirected to the login page when trying to open another page).
To make it extra-nasty, half of the time it just works as expected, also after half an hour...
Any help would be very much appreciated.
UPDATE:
Adding ini_set('session.gc_maxlifetime', 3600'); and `ini_set('session.cookie_lifetime', 3600); didn't help. I removed it again.
After that I had a look in the error logs and found this:
ap_pass_brigade failed with error 103: Software caused connection
abort
(problem is, I don't have access to the server settings - this is on a shared webspace...)
You can see the php configuration (php.ini) by phpinfo();
<?php
phpinfo();
Check the session.gc_maxlifetime values first then if you need to set it see the following ways.
You can set it with .htaccess file if you don't have permission for edit the php.ini file.
.htaccess
<IfModule mod_php5.c>
php_value session.cookie_lifetime 3600
php_value session.gc_maxlifetime 3600
</IfModule>
Even you can set it by ini_set();
<?php
ini_set('session.gc_maxlifetime', 3600);
For anyone who is interested: The session didn't actually expire, but the session variables disappeared (and reappeared again randomly).
This is discussed in a follow-up question I posted here:
php $_SESSION variables disappear and reappear randomly
You must have changed the session.name from default PHPSESSID to something else. Keep its default value session.name = PHPSESSID. Everything will be OK.
It's a PHP bug.
I've this little problem: PHP is not saving the cookie to my (cookie allowing) browser, other sites are fine but this one fails to save the session id in the cookie, ergo an inability to access necessary data.
The index page does a
require("includes/functions.php");
which successfully requires my functions file:
session_name('login');
// Starting the session
$expiretime = 60*60*24;
session_set_cookie_params($expiretime);
// Making the cookie live for 1 day
session_start();
However, the login cookie is not saving (checked via Firebug) and I've no reason why. Thanks for the help
Try displaying the session cookie parameters to make sure they are ok by running after session_start:
var_dump(session_get_cookie_params());
If path (or domain) doesn't match the prefix of your web app path, then you might have to set it explicitly:
session_set_cookie_params($expiretime, '/');
or
session_set_cookie_params($expiretime, '/myapp/');
I am setting a cookie containing a vlue in this format and redirecting to another page via the PHP header function. Here's the code,
setcookie("myCookie", $cookieValue, time() + $cookieLife, "/"); // cookieLife is expiration time in sec
header("Location: $baseURL/index.php"); // $baseURL is "http://localhost/mysite"
The cookie is getting set within the browser. However, I am unable to access the cookie value in the redirected page, i.e., "index.php". I am trying to access the cookie value with a simple echo like this,
echo $_COOKIE['myCookie'];
However instead of the cookie value, I get the following notice,
Notice: Undefined index: myCookie in /path/to/my/site/index.php on line 1
I have set the cookie path to "/" after looking at other solutions but am still unable to solve this.
Any help much appreciated.
EDIT :
I am testing this on XAMPP server, and the "mysite" here is actually an alias for another location on my hard drive. Could this be causing this issue?
I assume your cookie gets removed or dissapears once you've left the previous page.
Check if time() + $cookieLife is the desired time you want the cookie to live. The PHP setcookie function tells me that your $cookieLife is the time in seconds that you want your cookie to live, so make sure that it's the value you want it to be.
Use an extension to check your current cookies (and alter them if you need to). This way you can check and make sure if the cookie is living as long as you want it to (you already mentioned seeing the cookie being set, but I will include this just in case + for future visitors).
FireFox Extension: Web Developer
Chrome Extension: Cookies
I'm trying to make my login sessions last longer, so that people don't get logged out of my website too early. For example, making a blog post and losing it when they submit because php expired their cookie.
Ideally I'd like to give them say a 2 hour session where they won't be logged out, which will refresh every time they load the page (this code snippet below is before the header of each secure page)
This is what I am trying, but it comes up with an error for the setcookie() saying that there was a division by zero? What am I doing wrong here?
//How long sessions last
$hours = 2;
// php.ini setting required for session timeout.
ini_set('session.gc_maxlifetime',$hours*60*60);
ini_set('session.gc_probability',1);
ini_set('session.gc_divisor',1);
//Set the session parameters and start session
$sessionCookieExpireTime=$hours*60*60;
session_set_cookie_params($sessionCookieExpireTime);
session_start();
// Reset the expiration time upon page load
if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), $_COOKIE[session_name()], time() + $sessionCookieExpireTime, "/");
}
EDIT: Now working as the problem was non-standard quotes and apostrophes. Just in case anyone copies this code and uses it. Code above works now thanks!
If you would like you could add this for when your cookie expires:
time()+60*60*24*30
This is like saying that the cookie expires in 60secs, 60mins, 24h and so on. You should also check out a tutorial on cookies here: http://www.w3schools.com/php/php_cookies.asp
I'm using PHP5 here. I have made a login system that check's the username and password against the records in the database. I want to use sessions to store the logged value. For example, when I reach the zone where I "log in" the user succesfully:
if($errors = 0) {
$_SESSION['logged'] = "1";
}
The problem is that I want the $_SESSION['logged'] to stay active for let's say 5 minutes so when I do a if($_SESSION['logged'] == "1") after this time to return false. Also, I would like to delete this session after the user closes the browser. Basically, I want a session configuration so that the user can safely leave his desk and when him or somebody presses refresh after 10 minutes or enters again after the browser has been closed, the session to be already removed, and the access to be restricted.
Can anybody help? Thanks.
Use session_set_cookie_params() to change the lifetime of the session cookie. Note that by default, it is set to 0 which means that the cookie is set until the user exits the browser. You can do this in the following way:
/* Set to 0 if you want the session
cookie to be set until the user closes
the browser. Use time() + seconds
otherwise. */
session_set_cookie_params(0);
session_start();
Then check for the last activity time, updated each time someone visits a page.
if(($_SESSION['lastActivity'] + 300) < time()) {
// timeout, destroy the session.
session_destroy();
unset($_SESSION);
die('Timeout!');
} else {
$_SESSION['lastActivity'] = time();
}
Instead of setting it to one, why don't you set $_SESSION['logged_time'] = time(); and then check the time against time() in your application?
If you'd like to actually expire the entire session, the exact specifics can change depending on your session handler, but for the default session handler (and any other well behaved session handler) you'll want to check out http://us3.php.net/manual/en/session.configuration.php
You can change the configuration setting session.cookie_lifetime, e.g. in php.ini or a .htaccess file:
session.cookie_lifetime specifies the
lifetime of the cookie in seconds
which is sent to the browser. The
value 0 means "until the browser is
closed." Defaults to 0.
This means (I think) that you can't have both expiry based on a timeout and expiry when the browser is closed. So maybe the best bet is to keep the default and set your own timer in $_SESSION as others have suggested, thus rendering this answer pointless.
Sessions stay alive aslong as the user stays on your site. You will have to use cookies to set a specific timeout.