How can PHP developers ensure that only authenticated users have access to specific files on a web server?

PHP developers can ensure that only authenticated users have access to specific files on a web server by using session management and access control mechanisms. They can implement this by checking if a user is authenticated before allowing access to the files. This can be achieved by setting up a login system that verifies user credentials and creates a session upon successful authentication. The access control can then be enforced by checking the user's session before serving the requested files.

<?php
session_start();

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

// Serve the requested file
$file = $_GET['file'];
if(file_exists($file)){
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    readfile($file);
} else {
    echo "File not found.";
}
?>