File downloading is a common feature in web development, especially in admin systems or file distribution platforms. The core principle of file downloading is: the server reads the target file and sends it to the client via HTTP, which is then saved locally.
The process generally includes two phases:
PHP provides a built-in readfile() function that makes file downloads easy to implement. Here is a basic example:
$file = 'path/to/file'; // File path to be downloaded
$filename = basename($file); // Extract file name
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Explanation:
To avoid issues during file transfers, pay attention to the following points:
Using the __DIR__ constant ensures accurate file targeting:
$file = __DIR__ . '/path/to/file'; // Absolute path to file
You can detect and set the file's MIME type using mime_content_type():
$file = 'path/to/file';
$mime = mime_content_type($file); // Detect MIME type
header('Content-Type: ' . $mime);
If your filename includes non-English characters, use urlencode() to prevent encoding issues:
$file = 'filename.txt';
$filename = urlencode($file);
header('Content-Disposition: attachment; filename=' . $filename);
PHP’s readfile function combined with proper HTTP headers allows for a reliable file download implementation. By carefully handling file paths, MIME types, and filename encoding, you can ensure a smooth and secure file transfer experience. These methods are widely applicable and can be integrated into most PHP-based applications.