// Initialize session session_start(); // Check if user is logged in function is_logged_in() { if(isset($_SESSION['user_id'])) { return true; } else { return false; } } // Example usage if(is_logged_in()) { // Do something } else { // Redirect to login page header('Location: login.php'); }
// Include authentication library require_once('auth.php'); // Check if user is logged in if(is_logged_in()) { // Do something } else { // Redirect to login page header('Location: login.php'); }In both examples, the function 'is_logged_in' checks if the user is logged in by checking if the 'user_id' session variable is set. The library used in Example 2 is not specified in the code, but it could be a custom authentication library or a third-party library such as PHP Auth or Laravel's authentication system.