What are the best practices for managing PHP sessions to prevent them from expiring prematurely?

PHP sessions can expire prematurely due to various reasons such as server configurations, session.gc_maxlifetime setting, or session data size. To prevent this, it is important to properly configure session settings, handle session expiration gracefully, and regularly update session data to keep the session alive.

// Set session lifetime to 1 hour
ini_set('session.gc_maxlifetime', 3600);

// Start the session
session_start();

// Update session data to keep it alive
$_SESSION['last_activity'] = time();