A download response needs appropriate headers followed by the file content. Resolve the file from a controlled server-side location rather than accepting an unrestricted path from the URL.
$file = __DIR__ . '/downloads/report.csv';
if (is_file($file)) {
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="report.csv"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"my-data.csv\"");
$data="col1, col start and end col2,col3, \n";
$data .= "seond linedata here from site to download col1";
echo $data;
?>
session_start();
if (!isset($_SESSION['user'])) {
die("Unauthorized access!");
}
$file = 'path/to/file.zip';
if (file_exists($file)) {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
$file = 'large-file.zip';
$chunk_size = 8192; // 8KB chunks
$handle = fopen($file, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
flush(); // Send the data immediately
}
fclose($handle);
These examples demonstrate secure file handling, setting MIME types, and addressing large file downloads.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Ramesh | 28-08-2009 |
| Excellent tutorial....thanks a lot. | |
| mukesh | 16-03-2010 |
| how can i store .csv data in listbox by using php | |
| kapil agrawal | 21-03-2010 |
| good tutorials exciting to learn | |
| raymond | 27-12-2010 |
| please php script to display doc. file not image e g microsft word | |
| Moe | 08-01-2011 |
| Hello, The code below works on my localhost to download a file. However, on top of my downloaded file there are 160 lines of HTML tags. How can I eliminate these tags and just get the plain file? I appreciate your advice. $fd = basename($csv); header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename="".$fd."""); header("Content-Description: Download"); readfile($csv); | |
| pappu chauhan | 16-11-2012 |
| how to create download from server exact code. and how to create file read, file write, file append exact code. | |