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.

php Courses
php Courses
php Courses
Three Ways to Download Files in PHP

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

securityWeb DevelopmentPHPFile Download
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.