What are best practices for handling session timeouts and user inactivity in PHP applications?
Session timeouts and user inactivity can be handled in PHP applications by setting session expiration times and implementing a mechanism to check for user activity. One common approach is to use a combination of session timeouts and JavaScript to detect user activity and refresh the session accordingly.
// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);
// Start the session
session_start();
// Check for user activity and refresh session
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
session_unset();
session_destroy();
session_start();
}
$_SESSION['LAST_ACTIVITY'] = time();
Related Questions
- In what ways can DNS problems impact PHP scripts that rely on external resources like URLs in Linux environments?
- What is the significance of the dot (.) in regular expressions in PHP, and how does it impact text processing?
- How can the global availability of a returned value from a function be ensured in PHP?