PHP Sessions: Handling Session Expiry and Logout

I’m developing a PHP web application, and I’m working on implementing user authentication using sessions. The login functionality is working well, but I’m facing challenges with managing session expiry and providing a logout feature for users.

Here’s what I have so far:

// Starting a session on login
session_start();

// Checking user login status
if(isset($_SESSION['user_id'])) {
    echo "Welcome, User!";
    // Other protected content here
} else {
    header("Location: login.php");
    exit();
}

Now, I want to implement the following:

  1. Automatic Session Expiry: I’d like to set a session timeout, so users are automatically logged out after a period of inactivity.
  2. Logout Feature: Users should be able to log out manually by clicking a “Logout” button. This should destroy their session and redirect them to the login page.

Could someone provide guidance and code examples on how to achieve both of these goals? How can I implement session expiry with automatic redirection to the login page? And how can I create a secure logout mechanism that destroys the session? Any insights or best practices would be greatly appreciated. Thank you!

Please note that this is a Slim Framework specific forum.