What are some common issues with file downloads in PHP, such as incorrect file types being offered for download?

One common issue with file downloads in PHP is offering incorrect file types for download, which can result in users receiving unexpected files or errors when trying to open the downloaded file. To solve this issue, you can check the file type before initiating the download to ensure that only the correct file types are offered for download.

// Check the file type before initiating the download
$allowedFileTypes = ['pdf', 'doc', 'txt']; // Define an array of allowed file types

$filePath = 'path/to/file.pdf'; // Path to the file to be downloaded
$fileType = pathinfo($filePath, PATHINFO_EXTENSION); // Get the file type

if (in_array($fileType, $allowedFileTypes)) {
    // Set the appropriate headers for the file type
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
    readfile($filePath); // Output the file
} else {
    echo 'Invalid file type for download.';
}