Solved

automatic logout

Posted on 2010-09-19
26
597 Views
Last Modified: 2012-05-10
i am working with a content management system that logs me out
I think it is after x time of inactivity

i cant find where the x time is defined

could it be defined in sessions or cookies

could there be a session or cookie that says log out after x time

what else should i look for
0
Comment
Question by:rgb192
  • 14
  • 11
26 Comments
 
LVL 4

Expert Comment

by:upandrun3
ID: 33713173
HI rgb192,

Normally, stateful data like a login is handled through the session or a cookie.  The session system normally uses a cookie as well, but just tracks the session ID in the cookie and it's used each time you call a page.

There are two places I'd look for the timeout:

1.  Check to see if a cookie (either one that looks like it's tied to the login system or the session ID) has an expire time. If it's not set, then it should be when the browser closes.

2. The login/user system of the CMS you're using may have a field that also defines when the session expires. If you go to page before it expires, while logged in, I bet that field probably updates to a later date/time.  If you wait to long, then it may also cause a logout event.  If this looks to be the case, then you'll need to change/override/adjust that feature of the user/login system.

Hope this helps,
Pete
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33722951
If you could tell us which CMS you are using it would be easy to help you find the setting to configure the logout time.

In case you are using Joomla: the logout time is defined in Joomla's Administration, Menu "Site" -> "Configuration", menu item "System", "Session" panel on the right side. I experienced that after you change the setting (this is valid for most CMS's) you most likely have to logout and login again because the cookie's validity is only set once during login process.
0
 

Author Comment

by:rgb192
ID: 33762563
it is a custom cms

is there anyway to print information  (sessions, cookies)
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33767847
You can't read the cookie validity on the server-side, because the browser only transmits a valid cookie's values, not its expiry date. If you are using Firefox, open up "extras" -> "settings" -> "privacy" (I am on a german FF but I hope the translations match your browser's wording) and on the box you should find two links, one telling "display entire history" and the other something like "display a single cookie", click link two.

The now displayed list contains all cookies' values currently stored on your browser and if you've just logged in into your CMS, there should also be one (or probably more) cookie value(s) telling you which information is stored inside the browser, if clicked you'll see the cookie's expiry date in the box right below the cookie list.

Session duration settings are usually set inside php.ini, to see a list of the running configuration, use phpinfo() (if you don't know this command yet, upload the below script and open it up with your browser, there should be a "session" object telling you the currently set up session parameters).
<?php



phpinfo();



?>

Open in new window

0
 

Author Comment

by:rgb192
ID: 33780550
according to phpinfo();
session.gc_maxlifetime      1440      1440

does my session expire in 1440 seconds


also is phpinfo();
different when i log onto website
because there is different session info
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33781607
No, the "gc" in this variable stands for garbage collector and session.gc_maxlifetime tells after how many seconds inactive session variables (and thus data inside a database or files on a hard drive) should be cleared.
The interesting values will be the ones you can see on the set cookies inside your browser's cache. The best way to determine the default length of the session is to check the login routine of your custom CMS, there should be some script  handling the login process and that's the best point to start looking. If the CMS does not use PHP's session mechanisms (i.e. my CMS uses a custom session handling), you will most likely find a script where the session cookies are set manually, just do a text search on "setcookie" and you'll end up with a list of possible login routines. The third parameter of the setcookie() tells the validity period of the cookie, this could help you change the CMS' behaviour.
0
 

Author Comment

by:rgb192
ID: 33794895
so if the cookie expires.... does the it force the user to log out

I cant find any condition that leads the user to the logout page
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33796530
When a cookie is created, a validity period is assigned to the cookie because of two main reasons:
a) reducing the amount of temporary data stored in the browser cache (imagine that cookies would NEVER expire, this would lead to a whole lot of cookie files being stored in the cache)
b) security (both client-side - i.e. telling which pages the user has visited before - and server-side - leaving a system vulnerable because a user hasn't logged out)

In case a cookie's validity period has been exceeded, the browser simply discards this cookie, clearing it from the local cache. In case the expired cookie contains the login data of the CMS, the next time the formerly logged in user refreshes the page, the browser no longer transmits the cookie (because there simply is no cookie after the browser discarded it), resulting in the CMS redirecting the user to the login page again.
I assume that there is a condition like the one attach below which the server uses to identify the user. It's all a little different if the CMS uses PHP's session mechanism.
Any chance you could provide the source code of the CMS? That'll make finding the login/logout mechanism easy!
<?php 

if (isset($_COOKIE["username"])){

  // in case user logged in and cookie still valid

} else {

  header ("location: login.php");

}

?>

Open in new window

0
 

Author Comment

by:rgb192
ID: 33817703
i think this may be the code that determines time of logout
$sh = new session($db);
class session {
	private $_session;
	public $maxTime;
	private $db;

	public function __construct(PDO $database) {
		$this->db = $database;
		$this->maxTime['access'] = time();
		$this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');

		session_set_save_handler(array($this, '_open'), array($this, '_close'),	array($this, '_read'), array($this, '_write'), array($this, '_destroy'), array($this, '_clean'));
		register_shutdown_function('session_write_close');
		session_start();
		$this->_secure();
	}

	public function _open() {
		return true;
	}

	public function _close() {
		$this->_clean($this->maxTime['gc']);
		return true;
	}

	public function _read($id) {
		$getData = $this->db->prepare("SELECT data FROM sessions WHERE id = ?");
		$getData->bindParam(1, $id);
		$getData->execute();

		$allData = $getData->fetch(PDO::FETCH_ASSOC);
		$totalData = count($allData);
		$hasData = (bool) $totalData >= 1;
		$this->_clean($this->maxTime['gc']);

		return $hasData ? $allData['data'] : '';
	}

	public function _write($id, $data) {
		$getData = $this->db->prepare("DELETE FROM sessions WHERE id = ?");
		$getData->bindParam(1, $id);
		$getData->execute();
		$getData = $this->db->prepare("INSERT INTO sessions VALUES (?, ?, ?)");
		$getData->bindParam(1, $id);
		$getData->bindParam(2, $this->maxTime['access']);
		$getData->bindParam(3, $data);
		return $getData->execute();
	}

	public function _destroy($id) {
		$sql = "DELETE FROM sessions WHERE id = '$id'";
		dbquery($sql);
	}

	public function _clean($max) {
		$old = time();
		$old -= 1800;
		//$old = ($this->maxTime['access'] - $max);

		$getData = $this->db->prepare("DELETE FROM sessions WHERE access < ?");
		$getData->bindParam(1, $old);
		return $getData->execute();
	}
	public function _secure() {
		//Disabled due to conflicts when running many ajax requests. Race problem occurs, http://www.chipmunkninja.com/g@

		//Recreate SessionID and delete old sessions
		//$old_session_id = session_id();
		//session_regenerate_id();
		//$this->_destroy($old_session_id);
	}
}

/*--------------------------------------------------------------
	Session Related Functions
-------------------------------------------------------------- */
//This function handles authorization of all requested pages
function intiateAC() {
	global $db;

	if(!isset($_SESSION['loggedin'])) {
		$url = OW_URL . 'login.php';
		header('Location: '.$url);
        //echo 'you are not logged in';
	}
}

 {
	//Permissions are seperated by a , and a space keep in mind if there are check permission errors!!!!!
	if(in_array($permission,$_SESSION['permissions'])) {
		return true;
	}
	else {
		return false;
	}
}

Open in new window

0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33817874
Yes, the custom session handler uses the garbage collector's max lifetime setting, which makes solving the problem quite easy: simply increase "session.gc_maxlifetime" and try it again.
0
 

Author Comment

by:rgb192
ID: 33818714
>>simply increase "session.gc_maxlifetime"

which line is this
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33818782
You'll find the setting in php.ini, section "[Session]". If you don't find the line, PHP uses it's default value for session.gc_maxlifetime (should be the mentioned 1440 seconds), so you would have to add the line

session.gc_maxlifetime = 3600

and restart both your webserver and browser to refresh the session cookies on both sides.

Keep us posted.
0
 

Author Comment

by:rgb192
ID: 33835765
I want to decrease time for these  pages

but not everywhere  (using php.ini)

can I manually just decrease or set a variable in the code I have attached
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 7

Expert Comment

by:Swafnil
ID: 33838141
Your custom CMS will most likely have a central module handler (i.e. index.php handling all module requests), you could add a ini_set() in this central script to change the GC-setting for only the CMS and its pages. Just add the following line somewhere at the top of the index.php:

(Some more reading on ini_set(): http://de2.php.net/ini_set)
<?php

ini_set("session.gc_maxlifetime", "3600"); // overwrites PHP.ini's default value

?>

Open in new window

0
 

Author Comment

by:rgb192
ID: 33886935
in my cms ,
i saw these lines

ini_set('max_execution_time', 30*20);
ini_set('memory_limit', -1);


could I just change max_execution_time

and is   30*20=600
0
 

Author Comment

by:rgb192
ID: 33889916



in my cms ,
i saw these lines

ini_set('max_execution_time', 30*20);
ini_set('memory_limit', -1);


could I just change max_execution_time

and is   30*20=600





I changed this line to '2'

ini_set('max_execution_time', 2);


and I did not get logged out after one minute

0
 

Author Comment

by:rgb192
ID: 33889965
in my cms ,
i saw these lines

ini_set('max_execution_time', 30*20);
ini_set('memory_limit', -1);


could I just change max_execution_time

and is   30*20=600





I changed this line to '2'

ini_set('max_execution_time', 2);


ini_set("session.gc_maxlifetime", "2"); // overwrites PHP.ini's default value


and I did not get logged out after five minutes
0
 

Author Comment

by:rgb192
ID: 33890042
           $this->maxTime['access'] = time();
            $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');



how can I change this number to '2'
so I will log out in 2 seconds
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33892187
Good morning,

you are currently experimenting with the basic settings without knowing what they are used for, you should have a look at:

http://de.php.net/manual/de/ini.list.php

"max_execution_time" tells the server after which time (in seconds) a process must have been finished, in your case it will abort the execution of your CMS handler script after 2 seconds. So please remove that line, otherwise it could have serious effects on your CMS depending of the complexity of your modules (database-intensive modules can easily take several seconds to finish, now they would simply be aborted while running).

And why do you want to be logged out after 2 seconds? Remember, the session expires after two seconds, a normal roundtrip from client to server can easily take more than 2 seconds so it's likely you'll be logged out right after you have login.

Back to your last question:

Have you tried adding:

ini_set("session.gc_maxlifetime", "3600"); // overwrites PHP.ini's default value

somewhere close to the above ini_set() calls? It has to be set before the session is created, otherwise the changed value for gc_maxlifetime will have no effect (because it has been changed after the session has been created)?
0
 

Author Comment

by:rgb192
ID: 33898575

I added this line, which has no effect
ini_set("session.gc_maxlifetime", "2");

which has no effect because later in the code is this


     $this->maxTime['access'] = time();
            $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');

which I think takes from php.ini

so how to change
     $this->maxTime['access'] = time();
            $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');

to '2' so I can test

if it is '2', I will know it is working when I get logged of very quickly
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33902349
You are right, get_cfg_var() takes the setting directly from php.ini, while ini_get() uses the runtime config value.

So I would advise to use the below code instead of your current code:
$this->maxTime['access'] = time();

$this->maxTime['gc'] = ini_get('session.gc_maxlifetime');

Open in new window

0
 

Author Comment

by:rgb192
ID: 33921543

this line does nothing
$this->maxTime['gc'] = 1;


this line makes it so I cant even log in
$this->maxTime['access'] = 20;


I want to try with low numbers to see what is logging me out
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 33927434
$this->maxTime['access'] = 20;

will set the access time (this will be the time when the client initially logged in) to 20 seconds after PHP's start of time calculations (which is January 1 1970 00:00:00 GMT based on Unix Epoch, http://de.php.net/time ), so the session's validity period will expire directly after having logged in.

I just did some more reading on how sessions are handled inside PHP and here are my findings (and possibly a solution to your question):

* each script can set it's own GC maxlifetime value, thus changing its own maximum lifetime
* session data is stored in PHP's session.save_path if it has not been altered by ini_set('session.save_path', '/sessions');
* each script's GC will remove any session file that exceeded the current script's set gc_maxlifetime

To give a better example of what could happen inside your server and CMS, let's assume the following:

A.) We have your CMS with an altered session duration defined in your module loader:
ini_set("session.gc_maxlifetime", 3600); // 1 hour duration
before session_start() is called
B.) There is another script/application using sessions and PHP's ini values (with session.gc_maxlifetime = 1440)

1.) You log in into your CMS, session files are created in session.save_path with a validity of 3600 seconds
2.) 30 minutes have passed, your session is still valid
3.) another user calls a script outside of your CMS, this script's garbage collector first clears all old files with a validity period of 1440 seconds expired then continues
4.) You refresh your session, the CMS checks if $_SESSION['loggedin'] is set which isn't because it has been removed from the session cache in step 4
5.) You are redirected to the login page

This could be the answer to your problem:

[CODE]
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
ini_set('session.gc_maxlifetime', 3600); // max time in seconds
ini_set('session.save_path', '/sessions'); // you have to use an alternative directory for your CMS to avoid having other GC's remove your session files
session_start();  
[/CODE]

After changing your code, close your browser and start over again. A test scenario would be the following (if you are on windows):
- Open explorer and browse the session.save_path directory
- Log in with IE
- You should now see some new files inside the directory
- Wait until the session expires (i.e. use session.gc_maxlifetime of 10 for the test)
- Refresh the explorer, the files should still be there
- Log in with Firefox
- this should create another session while removing the files formerly created when you logged in with IE

Hope this will shed some light on this.
0
 

Author Comment

by:rgb192
ID: 33974588
session.gc_maxlifetime = 2
in php.ini
restarted webserver
and verified in phpinfo()


and this did not force a log out after 5 minutes
0
 
LVL 7

Accepted Solution

by:
Swafnil earned 500 total points
ID: 33977010
As stated above, this should force a logout after 2 seonds, you would have to set session.gc_maxlifetime = 300 for 5 minutes.
0
 

Author Closing Comment

by:rgb192
ID: 34038244
thanks
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now