How can PHP developers ensure that only specific file types are allowed for download, and prevent unauthorized access to sensitive files?

To ensure that only specific file types are allowed for download and prevent unauthorized access to sensitive files, PHP developers can use a combination of file type validation and access control measures. By checking the file type before allowing the download and implementing authentication and authorization mechanisms, developers can restrict access to only authorized users.

<?php
// Specify allowed file types
$allowedTypes = ['pdf', 'doc', 'txt'];

// Get the file extension
$extension = pathinfo($_GET['file'], PATHINFO_EXTENSION);

// Check if the file type is allowed
if (in_array($extension, $allowedTypes)) {
    // Implement authentication and authorization logic here
    // For example, check if the user is logged in and has the necessary permissions

    // If authorized, serve the file for download
    $file = $_GET['file'];
    $path = '/path/to/files/' . $file;

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($path) . '"');
    readfile($path);
} else {
    echo 'Invalid file type';
}
?>