Are there any security considerations to keep in mind when implementing a system to allow users to download files with original names in PHP?

When allowing users to download files with original names in PHP, it is important to prevent directory traversal attacks. This can be done by validating the file name to ensure it only contains alphanumeric characters and limiting the file path to a specific directory. Additionally, it is recommended to set appropriate file permissions to restrict access to sensitive files.

<?php
$downloadDirectory = '/path/to/download/directory/';

$fileName = $_GET['file'];

// Validate file name to prevent directory traversal
if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $fileName) && file_exists($downloadDirectory . $fileName)) {
    $filePath = $downloadDirectory . $fileName;
    
    // Set appropriate headers for file download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . filesize($filePath));
    
    // Output file contents
    readfile($filePath);
    exit;
} else {
    // Handle invalid file name or file not found
    echo 'Invalid file name or file not found';
}
?>