Are there any security risks to consider when allowing file downloads through PHP?

One security risk to consider when allowing file downloads through PHP is the potential for malicious files to be uploaded and executed on the server. To mitigate this risk, it is important to validate file types, restrict access to specific directories, and sanitize file names to prevent directory traversal attacks.

<?php
// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'pdf'];
$extension = pathinfo($_GET['file'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedTypes)) {
    die('Invalid file type.');
}

// Restrict access to specific directories
$filePath = '/path/to/files/' . $_GET['file'];
if (!file_exists($filePath) || strpos(realpath($filePath), '/path/to/files/') !== 0) {
    die('File not found.');
}

// Sanitize file name
$fileName = basename($_GET['file']);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
readfile($filePath);
?>