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);
?>
Related Questions
- What potential issues can arise when trying to extract version numbers from file names for caching purposes?
- What are the potential pitfalls of using a primary key for unique usernames in PHP?
- What potential pitfalls are present in the code provided for inserting data from .txt files into a database in PHP?