Time out php session

Set Timeout For Session In PHP

It provides the methods to set the timeout for the sessions in PHP. We can timeout the PHP session either programmatically or using the session.gc_maxlifetime configuration in PHPs ini file or by calling ini_set function.

We can use the sessions in PHP to store or persist the temporary data of the user for a specified duration as discussed in Using Sessions in PHP. PHP still needs to store the session id using Cookie on the browser or client-side as shown in Fig 1.

The session id stored on the browser in the PHPSESSID Cookie is the only way that PHP can use to identify the user session on the server-side. This still exposes the PHPSESSID Cookie for the attackers to steal it and query the server to process requests on behalf of the actual user. This leads to session hijacking where the stolen session id can be used by the attackers to access data from the active session. To prevent unauthorized requests, we can also use a strong cryptographic token which keeps on changing for every request made by the client.

Читайте также:  Html click and double click

We can further tighten the security by timing out the session as soon as it’s usage is over. This also erases the session cookie on the browser or client-side. This tutorial provides the methods to set the timeout for the sessions in PHP. We can timeout the PHP session either programmatically or using the session.gc_maxlifetime configuration in PHPs ini file or by calling ini_set function.

Update PHP ini

We can update the session.gc_maxlifetime by updating the PHPs ini file. I have provided a few examples as shown below.

# WampServer -> Example -> /bin/php/php7.2.14/php.ini

# XAMPP -> Example -> /php/php.ini

# Ubuntu -> Apache Example -> /etc/php/7.2/apache2/php.ini

Now search your php.ini file for session.gc_maxlifetime and update it as shown below.

; After this number of seconds, stored data will be seen as 'garbage' and
; cleaned up by the garbage collection process.
; http://php.net/session.gc-maxlifetime
;session.gc_maxlifetime = 1440
session.gc_maxlifetime = 900

I have updated the default value of 24 minutes to 15 minutes as shown above. Now restart Apache or Nginx server based on your server setup.

You may also timeout the cookies by changing the default value of 0 to the same value of session timeout. Make sure that you renew the Cookie expiry time on each request in such a case.

; Lifetime in seconds of cookie or, if 0, until browser is restarted.
; http://php.net/session.cookie-lifetime
;session.cookie_lifetime = 0
session.cookie_lifetime = 900

Use the ini_set Function

We can also use the ini_set function instead of changing the default session timeout duration as shown in the previous step. We can call the ini_set function to change session.gc_maxlifetime as shown below.

// Configure timeout to 15 minutes
$timeout = 900;

// Set the maxlifetime of session
ini_set( "session.gc_maxlifetime", $timeout );

// Also set the session cookie timeout
ini_set( "session.cookie_lifetime", $timeout );

// Now start the session
session_start();

// Update the timeout of session cookie
$sessionName = session_name();

if( isset( $_COOKIE[ $sessionName ] ) )
setcookie( $sessionName, $_COOKIE[ $sessionName ], time() + $timeout, '/' );
>

Programmatic Session Timeout

We can timeout a session programmatically without modifying the PHP configurations using the example as shown below. This works exactly in the way we want it without relying on the PHPs garbage collection which might not timeout the session at the specified duration as discussed in the previous sections.

// Start the session
session_start();

// Session timeout duration in seconds
// Specify value lesser than the PHPs default timeout of 24 minutes
$timeout = 900;

// Check existing timeout variable
if( isset( $_SESSION[ 'lastaccess' ] ) )
// Time difference since user sent last request
$duration = time() - intval( $_SESSION[ 'lastaccess' ] );

// Destroy if last request was sent before the current time minus last request
if( $duration > $timeout )
// Clear the session
session_unset();

// Destroy the session
session_destroy();

// Restart the session
session_start();
>
>

// Set the last request variable
$_SESSION['lastaccess'] = time();

Summary

This tutorial provided the details about the importance of session timeout and also provided the options to specify the duration to timeout the session.

Источник

How to change PHP session timeout

How to change PHP session timeout

A session is a way to store information (in variables) to be used across multiple HTTP Requests, to simulate a “state” across pages navigation.

Unlike a cookie, the information is not stored on the end users computer but in the application server.

For security reasons, sessions has a time limit to exist than they expire. PHP has a default timeout session limit and sometimes it is not the timeout your application needs. In this post we gonna learn how to change the PHP Session Timeout.

How long is a PHP session timeout

The PHP session timeout depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini file.

Typically the default PHP session timeout is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.

What is reasonable session timeout?

OWASP, one of the most authoritative web application security standards organizations, says about session timeouts:

“Insufficient session expiration by the web application increases the exposure of other session-based attacks, as for the attacker to be able to reuse a valid session ID and hijack the associated session, it must still be active. The shorter the session interval is, the lesser the time an attacker has to use the valid session ID. The session expiration timeout values must be set accordingly with the purpose and nature of the web application, and balance security and usability, so that the user can comfortably complete the operations within the web application without his session frequently expiring…Common idle timeouts ranges are 2-5 minutes for high-value applications and 15- 30 minutes for low risk applications.”

From the federal guideline perspective, the draft NIST 800-63B – Digital Identity Guidelines proposes the following recommendation for providing high confidence for authentication: “Reauthentication of the subscriber SHALL be repeated following no more than 30 minutes of user inactivity.”

So your sessions should not last longer than 30 minutes. Read the Session timeout considerations in this article.

Setting PHP Session Timeout

The timeout limit of the session in PHP is configured using two directives in the php.ini file:

  • session.gc_maxlifetime: It is used to set the time limit in seconds to store the session information in the server for a long time.
  • session.cookie_lifetime: It is used to set the expiration time limit for the PHPSESSID cookie.

Another way to set PHP session timeout is by using the ini_set() function in a PHP script.

Using php.ini settings for session timeout

Find the directive session.gc_maxlifetime and choose smallest possible. The session.gc_maxlifetime is a setting for deleting obsolete session ID. Reliance on this setting is not recommended. Developers should manage the lifetime of sessions with a timestamp by themselves.

It specifies the number of seconds after which data will be seen as ‘garbage’ and potentially cleaned up. Garbage collection may occur during session start (depending on session.gc_probability and session.gc_divisor ). Defaults to 1440 (24 minutes).

Find the directive session.cookie_lifetime and set it to 0 (zero). This value has a particular meaning. It informs browsers not to store the cookie to permanent storage. Therefore, when the browser is terminated, the session ID cookie is deleted immediately. If developers set this other than 0, it may allow other users to use the session ID. Most applications should use “0” for this.

If an auto-login feature is required, developers must implement their own secure auto-login feature. Do not use long life session IDs for this.

Using ini_set directives for setting session timeout

You can set session.gc_maxlifetime and session.cookie_lifetime using the ini_set(, ) function.

For this, at the begining of your script, call the function passing the directive and the desired value to set it.

See the following example:

php  //Set the session timeout for 2 seconds  $timeout = 2;  //Set the maxlifetime of the session  ini_set( "session.gc_maxlifetime", $timeout );  //Set the cookie lifetime of the session  ini_set( "session.cookie_lifetime", $timeout );  //Start a new session  session_start();  //Set the default session name  $s_name = session_name();  //Check the session exists or not  if(isset( $_COOKIE[ $s_name ] ))   setcookie( $s_name, $_COOKIE[ $s_name ], time() + $timeout, '/' );   echo "Session is created for $s_name.
"
;
> else echo "Session is expired.
"
;
> ?>

The following output will appear after executing the above script for the first time:

Session is created for PHPSESSID. 

And executing it again after 2 seconds the output will be:

Conclusion

The right session timeout for PHP applications can be configured using the global php.ini file or by scripts, what gives to developers more control on how much sessions should last.

References

Источник

How to Set Session Timeout in PHP: A Guide for Newbies

As a web developer, you might need to create websites with user logins, comment sections, and other features that require users to keep their accounts active. As such, it’s important to implement a way of limiting the time that users can spend on your website. This is called setting session timeout in PHP. Without this restriction, users can stay logged in on your website indefinitely.

This blog post will explain what session timeout in PHP is and why you would need it. Then we’ll provide step-by-step instructions for implementing session timeout in your own website projects. So keep reading to learn more!

What is session timeout in PHP?

A session is a temporary online exchange between two parties. A user can start a session with your website by logging into it, for example. The session is a two-way exchange: it allows users to interact with your website, and it also allows your website to interact with users. One example of how this exchange can be beneficial is that it lets you create user accounts on your website — and then log those users out when they’re done. This is called session timeout in PHP. Session timeout is the length of time that your website will keep a user logged in if they’ve already logged in.

Set the Session Timeout in PHP

Before you start, you’ll need to know your PHP version and whether your computer is set up for PHP development. Then you can follow these steps to set a session timeout. – Enable session timeout: The first thing you need to do is set your website to use session timeout in PHP. You can do this in your server’s configuration file.

It’s also worth noting that you can set the session timeout in the PHP configuration file (php.ini) by setting the session.gc_maxlifetime option. This option specifies the maximum lifetime of a session in seconds. For example, to set the session timeout to 30 minutes, you can set session.gc_maxlifetime to 1800 (30 minutes * 60 seconds):

To set the session timeout in PHP, you can use the `session_set_cookie_params` function. This function allows you to specify the lifetime of the session cookie in seconds. For example, to set the session timeout to 30 minutes, you can use the following code:

Источник

Оцените статью