To download a file in PHP, you can use the readfile function. This function reads a file and sends its contents to the output buffer, which can then be sent to the browser for download. Here is an example of how to use readfile to download a file:
<?php
$file = '/path/to/file.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;
}
This code first checks if the file exists, and if it does, it sends a series of HTTP headers to the browser to indicate that the file should be downloaded as an attachment. The Content-Type header specifies the MIME type of the file, and the Content-Disposition header specifies that the file should be treated as an attachment with the given file name. The Content-Length header specifies the size of the file in bytes. Finally, the readfile function is used to read the contents of the file and send them to the output buffer.
You can also use the fopen, fread, and fclose functions for php file download function to read the contents of a file and send it to the browser for download:
<?php
$file = '/path/to/file.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));
ob_clean();
flush();
$fp = fopen($file, 'r');
while (!feof($fp)) {
echo fread($fp, 1024);
flush();
}
fclose($fp);
exit;
}
This code opens the file with fopen, reads it in chunks with fread, and sends each chunk to the output buffer with echo. The flush function is used to send the contents of the output buffer to the browser.