What potential security risks are involved in allowing users to download files from a website using PHP?

Allowing users to download files from a website using PHP can pose security risks such as malicious file uploads, directory traversal attacks, and executing arbitrary code. To mitigate these risks, it is essential to validate and sanitize user input, restrict file types, and store files outside the web root directory.

<?php
// Validate and sanitize user input
$filename = filter_var($_GET['filename'], FILTER_SANITIZE_STRING);

// Restrict file types
$allowedTypes = ['pdf', 'doc', 'txt'];
$fileExt = pathinfo($filename, PATHINFO_EXTENSION);
if (!in_array($fileExt, $allowedTypes)) {
    die('Invalid file type.');
}

// Store files outside web root directory
$filePath = '/path/to/files/' . $filename;

// Download file
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
readfile($filePath);
?>