php session timeout - php

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).

Related

PHP mixing up sessions

I've been having problems with sessions for some days now in my production environment
I've already tried to find the solution in tons and tons of answers here in stack overflow, but none seem to work for me
User A logs in
User B logs in. Now when you go back to User A
his session was overwritten by User B. So I have two users 'sharing' the
same session.
Side notes:
I have session_start() on the very top of every page using session variables
I'm using https with a valid certificate
Cache is not the problem, I've already tried to set headers to avoid caching
I'm using PHP 5.4 (I was using 5.6 before and downgraded hoping it would solve my problem) and this is my PHP.ini:
session.save_path = "/tmp"
session.cookie_secure = 1
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.entropy_length = 32
session.cache_limiter = nocache
session.cache_expire = 180
session.hash_function = sha256
And this is the basic structure of my authentication page:
session_start();
... // after connection with the database I retrieve id and name
$_SESSION['id_logado'] = $user_id;
$_SESSION['nome_logado'] = $user_name;
I've already double checked every line of code in every page. There is no variable name $id_logado so it should not interfere with that. Cache is probably not the problem because I have headers to avoid caching just after session_start. I've contacted bluehost to ask for help and of course they have no idea and are blaming myself.
I found a solution.
After further investation I noticed that the /tmp folder had only one session file, with a big size. For some reason sessions were not being saved to new files and were being 'added' to the same one.
Solution: I've created a new folder inside my home drive and granted 777 permissions. Updated my php.ini file to use that folder instead of /tmp and now I have tons of sessions being properly generated.

Session Lifetime on PhpMyAdmin

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();

PHP session variables not being maintaned

I have an application that has been working with session variables no problem. I start the session before the headers on every page that uses when, it has been fine then it seems all of a sudden I'm getting an undefined index error when I navigate to a page other than the one that sets up the session variables. But only on some browsers. Sometimes sessions are maintained and sometimes they aren't.
It seems that cookies aren't being stored some of the time. I've done checks using different browsers and sometimes cookies are stored and sometimes not.
I did an experiment. I was using firefox to use to app and I was keeping an eye on the tmp folder where the sessions are stored. I cleaned it out. Using firefox I started using the app, using all the pages that sessions were in use and at the end I checked the tmp folder and it had one session file in there.
Did the exact same with internet explorer and there are now 7 different session files.
I'm using PHP 5.3.0 with the WAMP stack. Apache 2.2.11. Session support is enabled in my phpinfo().
I call a var dump on the first page and it prints out the session data. On any subsequent pages the session variable is empty.
<?php var_dump($_SESSION); ?>
array(0){}
Can anyone help me figure out a solution to this?
UPDATE - PHP INI SESSION settings
Directive Local Value Master Value
session.auto_start Off Off
session.bug_compat_42 On On
session.bug_compat_warn On On
session.cache_expire 180 180
session.cache_limiter nocache nocache
session.cookie_domain 82.68.26.169 82.68.26.169
session.cookie_httponly Off Off
session.cookie_lifetime 0 0
session.cookie_path / /
session.cookie_secure Off Off
session.entropy_file no value no value
session.entropy_length 0 0
session.gc_divisor 1000 1000
session.gc_maxlifetime 1440 1440
session.gc_probability 1 1
session.hash_bits_per_character 5 5
session.hash_function 0 0
session.name PHPSESSID PHPSESSID
session.referer_check no value no value
session.save_handler files files
session.save_path c:/wamp/tmp c:/wamp/tmp
session.serialize_handler php php
session.use_cookies On On
session.use_only_cookies On On
session.use_trans_sid 0 0
UPDATE - Solution
Because my app was using iframes pulling in pages from another domain (which i created) the cookies i was trying to set were being blocked. Setup a P3P header and the problem seems to be solved!
My suggestion from your previous question still stands: please compare session ids.
The solution might be as simple as your browser not accepting session cookies.
You retrieve the session id by calling session_id(). Do that right after session_start() it should give you a constant value if the session is the same. Otherwise for every request a new session is instantiated.
Also check C:\wamp\tmp. A gazillion files in this directory might indicate fresh sessions for each request.
EDIT Since we've confirmed new sessions per request, it's time to find out whether session cookies are accepted. Check the settings of your browser and confirm that a cookie for your domain (I guess it's "localhost") with the name PHPSESSID can be found.
Do you call session_start() on every page that accesses session data?
Edit: And do you receive the same session ID every time?
Also, could there be some error or warning you're missing (e.g. headers already sent) due to settings?
here is the sense in
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$_SESSION['saveddata'] = $row;
}
it rewrites $_SESSION['saveddata'] value on each iteration. may be you meant something like
$_SESSION['saveddata'][] = $row;
it makes sense for $atid = $_SESSION['saveddata']['autotaskid'];
Review your session settings. You have a full list with:
<?php
phpinfo();
?>
Scroll down to the "Session" table.
Particularly, make sure that the session.save_path directory exists and is writeable.
When a new session ID is created with each request, most likely it is an issue with your session paths (save_path and cookie_path) and chances of this happening are greater if you're hosting different applications on one server (shared hosting) and some of these applications also implement sessions.
This results in conflicts in your /tmp directory.
You could change the config of your ini file, but it's best to configure these parameters during runtime.
session_set_cookie_params(0, "/app", ".domain.com");//set session cookie parameters
session_save_path("/home/../public_html/app/sess");//set directory of this app's session data
session_start();//start session
I hope that helps everyone having this issue. #CodeOn
I solved this problem on my local WAMP by clearing out the \tmp directory of old sessions.

PHP sessions causing Apache to hang indefinitely

The problem is that every so often a page that writes to a Session will cause apache to hang forever for a particular session. Once this error occurs for one user any further modifications to any session of any user will cause the website to hang for this user.
This problem has been my sole focus for days. I have a development VPS running Windows 2003 and default latest version of XAMPP using the standard PHP session handler. The code in question actually runs on two other machines perfectly normally so although my common sense says it’s a web server configuration issue but at this point I am willing to try anything.
On further investigation there are no errors in the Apache, PHP or System event log. Resources are abundant and there is no “AJAX shit storm” or more than a couple writes to a session per page. I have also implemented session_write_close() wherever possible to try and help elevate the problem.
I have checked the session’s directory which is set to “C:\windows\Temp” and found that once a user enters this hanging phase that the corresponding session file is exclusively locked and the only way to resolve this is to stop Apache and wait a few moments for the files to become unlocked and delete them. I am not wondering if deletion is required.
The Sessions themselves only contain 4 bits of information. ShoppingCartID, UserID, UserLevel and Refering URL and are alphanumerical with an occasional slash.
My PHP.INI’s session section is configured like this:
session.save_handler = files
session.save_path = "C:\WINDOWS\Temp"
session.use_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 100
session.gc_maxlifetime = 1440
session.bug_compat_42 = 1
session.bug_compat_warn = 1
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 4
I have tried everything I can think of and the whole problem is now a blur to me. Any ideas would be appreciated and thanks for your time reading this :)
It could be your session files getting locked by Windows or some php.ini settings not done properly. Please SEE HERE
Almost want to say its the lock files.
Is it possible your app internally requests a page from the same site again internally? You could be hitting a race condition of sorts where page A fires up, locks the session, and then somehow triggers a request to itself, or page B, which also tries to re-start the session, which is now locked, and the request hangs.
Otherwise, if the hang is caused by the session file being locked, I'd suggest using something like SYSInternal's 'Handle' to get a list of what processes are using the session file in question.

What is the default lifetime of a session?

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

Categories