Skip to content
PHP Logo

What are the potential pitfalls of using the readfile function in PHP for downloading files?

Potential pitfalls of using the readfile function in PHP for downloading files include the lack of error handling, potential memory issues when dealing with large files, and vulnerability to path traversal attacks if the file path is not properly sanitized. To mitigate these risks, it is recommended to use appropriate error handling, limit the file size that can be downloaded, and ensure that the file path is secure.

php
$file = 'example.txt';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    echo 'File not found.';
}