How can PHP be used to restrict access to files only to logged-in users?

To restrict access to files only to logged-in users in PHP, you can check if the user is logged in by verifying their session credentials before allowing them to access the file. This can be done by setting up a login system that stores user login status in sessions and then checking this status before serving the file.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    // Redirect user to login page or display an error message
    header("Location: login.php");
    exit();
}

// Serve the protected file here
?>