PHP Download File
Syntax
The readfile()
function in PHP is used to read a file and write it to the output buffer. This can be used to download a file to the user's computer.
readfile($filename);
Example
Here is an example of using readfile()
to download a file when a user clicks on a link:
<a href="download.php?file=myfile.pdf">Download PDF</a>
// download.php
$file = $_GET['file'];
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.';
}
Output
When a user clicks on the "Download PDF" link, the file will be downloaded to their computer.
Explanation
The code in download.php
checks if the file exists, sets several headers to ensure the file is downloaded as an attachment, and then uses readfile()
to output the file content to the user's browser.
Use
The readfile()
function can be used in PHP to download files to a user's computer. This is useful for allowing users to download files such as PDFs, images, or other documents.
Important Points
- The
readfile()
function reads a file and writes it to the output buffer in PHP. - Several headers must be set to ensure the file is downloaded as an attachment.
readfile()
can be used to download files such as PDFs, images, or other documents.
Summary
PHP's readfile()
function can be used to download files to a user's computer. By setting the appropriate headers, files can be downloaded as attachments. This is a useful feature for allowing users to download files such as PDFs or images from a website.