What are some common pitfalls to avoid when using PHP to handle file downloads and managing file paths?
One common pitfall to avoid when handling file downloads in PHP is not properly sanitizing user input, which can lead to security vulnerabilities such as directory traversal attacks. To mitigate this risk, always validate and sanitize user input before using it to construct file paths.
// Sanitize user input to prevent directory traversal attacks
$filename = basename($_GET['filename']);
$filepath = '/path/to/files/' . $filename;
// Check if the file exists before proceeding with the download
if (file_exists($filepath)) {
// Perform file download logic here
} else {
echo 'File not found.';
}