What are the best practices for handling user sessions, login, and logout functionality in PHP to ensure smooth operation of timers and data storage?

When handling user sessions, login, and logout functionality in PHP, it is important to use session management functions provided by PHP to ensure smooth operation of timers and data storage. This includes starting the session, setting session variables for user authentication, and properly destroying the session upon logout.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is logged in
    // Perform necessary actions
} else {
    // User is not logged in
    // Redirect to login page
    header("Location: login.php");
    exit();
}

// Logout functionality
if(isset($_POST['logout'])){
    // Destroy the session
    session_destroy();
    // Redirect to login page
    header("Location: login.php");
    exit();
}