How can PHP scripts be used to control access to files and prevent unauthorized users from viewing them?

To control access to files and prevent unauthorized users from viewing them using PHP, you can use a combination of authentication checks and file permissions. One common approach is to check if the user is logged in and has the necessary permissions to access the file before serving it to them.

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

// Check if the user has the necessary permissions to access the file
if(!hasPermission($_SESSION['user_id'], $file)) {
    // Display an error message or redirect to a forbidden page
    echo "You do not have permission to access this file.";
    exit;
}

// Serve the file to the user
readfile($file);

// Function to check user permissions
function hasPermission($user_id, $file) {
    // Implement your logic to check if the user has permission to access the file
    // For example, you can check if the user is the owner of the file or belongs to a specific user group
    return true; // Return true if the user has permission, false otherwise
}
?>