Three Ways to Download Files in PHP
The article explains three PHP methods for file downloading: a direct link, a parameter‑based redirect that checks file existence, and a streamed download using head() and fread() with proper HTTP headers, comparing their simplicity and security implications.
This article demonstrates three PHP techniques for serving file downloads.
1. Direct link: embed a button with an anchor tag, for example <button><a href="http://localhost/down.zip">Download File</a></button> , which lets the browser download the file directly.
2. Parameter‑based redirect: pass a query parameter (e.g., http://localhost?f='down' ) and use PHP to construct the file name, verify its existence, and issue a Location header to the file URL, returning a 404 response if the file is missing. Sample code: <?php $down = $_GET['f']; $filename = $down . '.zip'; $dir = "down/"; $down_host = $_SERVER['HTTP_HOST'] . '/'; if (file_exists(__DIR__ . '/' . $dir . $filename)) { header('Location: http://' . $down_host . $dir . $filename); } else { header('HTTP/1.1 404 Not Found'); } ?>
3. Streamed download with head() and fread() : open the file in binary mode, send appropriate headers ( Content-Type: application/octet-stream , Accept-Ranges: bytes , Content-Length , Content-Disposition: attachment; filename=... ), read the file with fread , echo its contents, then close the handle. Sample code: <?php $file_name = "down.zip"; $file_dir = "./down/"; if (!file_exists($file_dir . $file_name)) { header('HTTP/1.1 404 NOT FOUND'); exit; } $file = fopen($file_dir . $file_name, "rb"); header('Content-Type: application/octet-stream'); header('Accept-Ranges: bytes'); header('Content-Length: ' . filesize($file_dir . $file_name)); header('Content-Disposition: attachment; filename=' . $file_name); echo fread($file, filesize($file_dir . $file_name)); fclose($file); exit; ?>
The first two methods are straightforward but expose the actual file path, whereas the third method hides the path and provides better security.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.