Tag Archives: Session

Automatic session timeout/logout using PHP after X Minutes of Inactivity/Idle time

PHP Automatic Session Expire after X Minutes of Inactivity/Idle time

 Automatic session timeout/logout using php

 

Session timeout is a notion and the only way you make you sure that no session ever will survive after X minutes of inactivity. Session timeout or Session expire depends on the server configuration or the relevant directives (session.gc_maxlifetime) in php.ini.

 

Typically the default is 1440 seconds(24 minutes), but you can alter the default to something else. Below are some Session configurations.

 

http://php.net/manual/en/session.configuration.php

 

You can update this easily and without writing custom logic.

 

If your sessions are implemented with cookies (which they probably are), and if the clients are not malicious, you can set an time limit on the session duration by tweaking certain parameters. If you are using PHP’s default session handling with cookies, setting session.gc_maxlifetime along with session_set_cookie_params should work for you like this:

 

// server should keep session data for 1 hour
ini_set('session.gc_maxlifetime', 3600);

// each client remember their session id for exactly 1 hour
session_set_cookie_params(3600);

session_start(); // ready to go!

 

You can also put this in .htaccess file with a slight change in syntax.

 

php_value session.gc_maxlifetime 3600

php_value session.gc_probability 1

php_value session.gc_divisor 1

 

session.gc_probability, and session.gc_divisor directives: PHP has garbage collection it uses to clean up sessions that have expired, otherwise on a site with a lot of users accessing the site could cause a huge amount of session files to be continually generated. Garbage collection does not happen automatically and needs to be incorporated into your system maintenance routines.

 

You can also make a custom script that automatically logout a user if user is inactive (not performed any action or idle) for X minutes.

 

1) When user logged in, start session, start session expiry time, like this:

 $_SESSION['expire'] = time() + X*60; 

We took current time, added X minutes in it and stored this in session.

 

2) At every page check that if X minutes (for above script) have been passed or not make a file as include that in that page, like this:

If yes, clear session and logout, like this:

if(time() > $_SESSION['expire']){
    session_destroy();
    session_write_close();
    session_unset();
    $_SESSION = array();
}

 

And then redirect to login page.

 

3) In else statement (if X minutes have not passed), reset time (takes current time and add X minutes in it and restore in session named ‘expire’) stored in session, like this:

else { $_SESSION['expire'] = time()+X*60; }

 

and do nothing – don’t clear sessions, don’t redirect to login page, so that user may stay at website, as much time as he is active.

 

You can also do this purely using JavaScript. Start an countdown timer. Then wait for activity and reset this timer. If there is no activity and timer goes off, you can call your logoff sequence.


/* Resets the timer. The timer is reset on events
   (mouse-move,mouse-click,key press,scrolling),
   these events occurs indicates that user is active on the application:
*/

<body onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">

<script type="text/javascript">
 
//the interval 'timer' is set as soon as the page loads

var timer = setInterval(function(){ auto_logout() }, 20000);

// the figure '20000' (20 seconds) indicates how many milliseconds the timer be set to.

//e.g. if you want it to set 5 mins, calculate 5min= 5x60=300 sec => 300,000 milliseconds.
 
function reset_interval(){

    //first step: clear the existing timer
    clearInterval(timer);
   
    //second step: implement the timer again
    timer = setInterval(function(){ auto_logout() }, 20000);
    //..completed the reset of the timer

}

function auto_logout(){

    //this function will redirect the user to the logout script
   
    if(confirm("You have been logged out from the application, Press OK to login again!")){
        window.location="your_logout_script.php";
    }

}

</script>

Hope it will works, let me know by your valuable comments if you need any more assistance.

PHP: Difference between cookies and session

What is the difference between cookies and session?

 

HTTP is a stateless protocol.
That mean, that treats each request as an independent transaction that is unrelated to any previous request. So, how about the request we want to make frequently, like username or id? As you know, we could store our data in COOKIE. When we store data in COOKIE, the browser will send the cookie data to server for each request. We already could use SESSION for this kind of task. So, what is difference between SESSION and COOKIE?

 

COOKIE
A cookie is a text-only string that takes a place in the memory of user’s browser. If the lifetime of the cookie is set to be longer than the time user spends at that site, then this string is saved to file for future reference. User could be disabled the cookie in their browser setting.

 

SESSION
A session is an object associated with a client connection to the server. it has the ability to carry information related to the client,session values are store in server side not in user’s machine. A session is available as long as the browser is opened. User couldn’t be disabled the session. We could store not only strings but also objects in session.

Session files are deleted automatically by php according to garbage collection settings.

 

1.The main difference between cookies and sessions is that cookies are stored in the user’s browser(hard disk), and sessions are not,cookies are browser dependent and sessions are not dependent on client’s browser settings

 

2.A cookie can keep information in the user’s browser until deleted. But Session work instead like a token allowing access and passing information while the user has their browser open.

 

3.The difference between sessions and cookies is that a session can hold multiple variables or objects, and you don’t have to set cookies for every variable. By default, the session data is stored in a cookie with an expiry date of zero, which means that the session only remains active as long as the browser. When you close the browser, all the stored information is lost. You can modify this behavior by changing the “session.cookie_lifetime” setting in “php.ini” from zero to whatever you want the cookie lifetime to be.

 

You can get the best! Once you know what each does, you can use a combination of cookies and sessions to make your site work exactly the way you want it to do.

 

Session vs Cookie or cookies and session in php

Complete guide of cookies and session in php

 

SESSION

 

Many New PHP developers are often confused whether to use sessions or cookies for their websites. Both cookies and sessions have their advantages and drawbacks. PHP developer should first understand the differences between each so that he can choose better option according to need.

 

Sessions are PHP’s built in method for handing cookies. According to PHP.net, sessions are “a way to preserve certain data across subsequent accesses.”

 

Whenever PHP creates a new session, it generates a sessionID (session_id())this session id is then either stored on the user’s computer as a cookie or in some cases, attaches itself to the end of each page’s URL as a query string.The actual information stored is not stored on the user’s computer or client machine.PHP stores the information in the session on the server in some kind of database or a text file( you can see this in phpinfo “session.save_handler“).In the background processes on the server, PHP runs a garbage collecting process that destroys all sessions that have been inactive for twenty-four minutes (in phpinfo “session.gc_maxlifetime“)thus, sessions are a way of storing client information on a server.

 

Every time on client request (values do not necessarily have to be changed) a session, the garbage collector resets its twenty-four minute countdown for deletion.Thus, a user cannot leave a site and come back in an hour or two (time set in php.ini file) and expect the session to still be alive.In addition, a user’s computer deletes all sessionIDs every time the user closes the browser.Thus, the only real advantage of using sessions is that they allow a PHP developer to hide what information is being stored from the users and hackers.However, hackers can hijack sessions with a cookie grabber, so one cannot argue that sessions are much more secure than cookies.

The only security advantage of sessions is that they hide information; thus, if a website stored a user’s (encrypted) password in a cookie and a hacker somehow obtained the cookie, the hacker could run a password cracker(bad software) on the encrypted password to get it, whereas a session hijacker would have only have access to the account, not the encrypted password.PHP developers should use sessions only for things that require the short-term preservation of data.Overall, sessions serve as a short-term method for preserving data across pages while hiding information from users and hackers.

 

COOKIE

PHP.net defines cookies as “a mechanism for storing data in the remote browser and thus tracking or identifying return users.”

Cookies maintain a set interval of time even if the user closes the browser (unless of course he clears his cookies or it expire). The only disadvantage to using a cookie is that the information is stored locally on the user’s computer in a text file. Therefore, hackers who use cookie stealer can access the information as well as anyone with physical or remote access to the computer’s files, this can be a security threat. However, a well-coded website prevents cookie grabbers from working, and thus eliminates most of the security threat. However, it is important to keep in mind that users can easily change the value of a cookie, so treat anything inside of a cookie as malicious user input. Therefore, PHP developers should use cookies as a long-term solution to preserve data across pages and sessions.

 

Overall, sessions serve as temporary information holder that can hide information, whereas cookies serve as both a temporary and long-term information holder. After the difference between sessions and cookies is clear, making the right choice for a website is rather simple. Though sessions may seem easier to use than cookies, never doubt the power and ease of using cookies.

 

Hope this will help 🙂

 

Do you want to know a quick answer of differences between session and cookie?