Skip to content
Tutorials Center
My learning

Topics

Lesson 136 of 147 ยท Projects

Project: File Downloader

Build a secure PHP file downloader in four stages - safe file lookup, Content-Disposition headers, streaming large files in chunks, and partial downloads with HTTP Range requests.

Almost every site offers downloads: invoices, reports, exports, e-books. The easy way is to put the files in a public folder and link to them. That stops working the moment a file must be private (only the buyer may download it), counted, renamed for the visitor, or generated on the fly. Then a PHP script has to stand between the browser and the file and send it with the right headers.

You will build that script in four stages: (1) find the file safely, (2) send it with the right headers so the browser downloads it with a good file name, (3) stream large files without exhausting memory, and (4) support partial requests (HTTP Range) so downloads can resume. As in the other projects there is no web server in the editor, so the code builds the response (status, headers, body) as a value you can inspect. The last section shows the tiny piece that sends it for real.

Prerequisites: File Handling, HTTP headers and redirects, File Uploads and Secure Coding.

The plan

flowchart TD
  A["GET /download?id=report-2026"] --> B{"Known id?"}
  B -->|"no"| C["404"]
  B -->|"yes"| D{"File exists inside the storage folder?"}
  D -->|"no"| C
  D -->|"yes"| E{"Range header?"}
  E -->|"no"| F["200 + full file"]
  E -->|"valid"| G["206 + partial content"]
  E -->|"invalid"| H["416 Range Not Satisfiable"]

The visitor asks for an id, never for a path. The server maps the id to a file it controls.

Stage 1: find the file safely

The most dangerous version of this script is readfile($_GET['file']). A visitor who sends ../../etc/passwd or ../.env reads files you never meant to publish. This is called path traversal. Two rules prevent it:

  1. Never take a path from the request. Take an id and look it up in a map (or a database table) that you control.
  2. As a second line of defence, resolve the final path with realpath() and check that it starts with your storage folder.
PHP Stage 1: lookup with a traversal check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The traversal attempt is rejected twice: it is not in the id map, and its resolved path would not be inside the storage folder. Keep both checks; one mistake in the list should not expose files.

Store the files outside the web root (the folder your server publishes). Then even a bug in this script cannot expose them by a direct URL.

Stage 2: headers that make the browser download

A browser decides what to do with a response from its headers:

Header Purpose
Content-Type The media type. application/octet-stream means "unknown binary data".
Content-Disposition: attachment; filename="..." Tells the browser to save the file instead of showing it, and suggests a name.
Content-Length The size in bytes, so the browser can show a progress bar.
X-Content-Type-Options: nosniff Stops the browser from guessing a different type.
Cache-Control private for protected files so shared caches do not store them.
Accept-Ranges: bytes Announces that partial downloads are supported (stage 4).

File names with spaces, quotes or non-ASCII letters need care. The reliable form sends an ASCII fallback in filename and the real UTF-8 name in filename*=UTF-8''..., percent-encoded with rawurlencode().

PHP Stage 2: building the response headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

rawurlencode() turns รฉ into %C3%A9, which every modern browser decodes from filename*. Never put the visitor's raw text into a header: a line break in a file name would let an attacker inject extra headers (PHP's header() rejects newlines, but your own code should not depend on that). See HTTP Headers and Redirects.

The type of a file chosen by a visitor is not trustworthy. If users can upload files and others download them, serve everything with Content-Disposition: attachment and nosniff, or an uploaded HTML or SVG file could run script on your domain.

Stage 3: streaming big files

file_get_contents() followed by echo loads the whole file into memory. A 2 GB video would need 2 GB of RAM per download. Instead, read and send small chunks. readfile($path) does exactly this for you in one call and is the right default. When you need control (limits, partial reads, progress), loop with fread().

Two production details: close the session before a long download (session_write_close()), or the visitor's other requests wait for the session lock; and call set_time_limit(0) so a slow connection does not hit PHP's time limit, while still checking connection_aborted().

PHP Stage 3: sending a file in chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For very large traffic let the web server do the work. X-Sendfile (Apache) and X-Accel-Redirect (nginx) let PHP authorize the request and then hand the actual transfer to the server, which is much faster. Your PHP code stays the same except for one header instead of the loop.

Stage 4: resumable downloads with Range

When a download is interrupted, browsers and download managers ask for the rest with Range: bytes=START-END. A server that supports it answers 206 Partial Content with Content-Range: bytes START-END/TOTAL. A request outside the file gets 416 Range Not Satisfiable. Three forms matter:

  • bytes=500-999: from byte 500 to 999 (inclusive)
  • bytes=500-: from 500 to the end
  • bytes=-200: the last 200 bytes
PHP Stage 4: parse Range and build the response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The sizes line up with stage 3: for a 206 you call streamFile($path, $start, $end - $start + 1, ...). A full implementation also needs If-Range and multi-range support, which download managers rarely use; if you only handle a single range and answer anything else with the full file, you are within the standard.

Running it for real

Put the pieces together in one script. This is what you deploy; the code cannot run in the editor because it sends real headers.

PHP
<?php
// download.php
declare(strict_types=1);
session_start();
// ...authorization check here, e.g. does $_SESSION['user_id'] own this file?
session_write_close();                                  // do not block the visitor's other requests

$found = locate($storageDir, $_GET['id'] ?? '');        // stage 1
if ($found === null) {
    http_response_code(404);
    exit('Not found');
}

$response = respond($found['size'], $_SERVER['HTTP_RANGE'] ?? null);   // stage 4
http_response_code($response['status']);
foreach (downloadHeaders($found) as $name => $value) {                // stage 2
    header("$name: $value");
}
foreach ($response['headers'] as $name => $value) {
    header("$name: $value");                                          // Content-Range / Length override
}

if ($response['status'] !== 416) {
    $start = $response['status'] === 206 ? (int) explode('-', substr($response['headers']['Content-Range'], 6))[0] : 0;
    set_time_limit(0);
    streamFile($found['path'], $start, $response['bytes'], function (string $data): void {   // stage 3
        echo $data;
        flush();
        if (connection_aborted()) {
            exit;
        }
    });
}

Test it with curl -I for the headers, curl -r 0-99 -o part.bin for a range, and by cancelling a download in the browser. Also log each completed download (who, which file, when) if you need counts.

Ideas for extending the project

  • Expiring links: sign the id and an expiry time with hash_hmac() so a link works for 10 minutes only (see Cryptography).
  • Generated files: stream a CSV straight from the database, as in CSV Files, without ever writing it to disk.
  • Download counters stored with PDO.
  • Bandwidth limits by sleeping between chunks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the download script take an id instead of a file path from the request?

    If the visitor chooses the path, they can walk out of the storage folder. An id looked up in your own map can only reach files you listed.
  2. 2. What does Content-Disposition with the value attachment do?

    Without attachment the browser may try to display the content. The filename parameter proposes the name to save.
  3. 3. Why is readfile() or a fread() loop better than file_get_contents() plus echo for large files?

    Streaming in chunks keeps memory use constant, however large the file is.
  4. 4. Which status code answers a valid Range request for part of a file?

    206 Partial Content, with a Content-Range header. 416 is for a range that cannot be satisfied.
  5. 5. Why call session_write_close() before streaming a long download?

    PHP locks the session file while a request holds it open. A long download would otherwise freeze every other page for that visitor.

Summary

  • Never accept a file path from the request: map ids to files, resolve with realpath() and check the storage prefix; keep files outside the web root.
  • Content-Disposition: attachment triggers the save dialog; use filename*=UTF-8''... for non-ASCII names and add nosniff and a private cache policy.
  • Stream with readfile() or a chunked fread() loop to keep memory flat; release the session lock first.
  • Support Range with 206 and Content-Range (and 416 for impossible ranges) so downloads can resume.
  • Let nginx or Apache send the bytes with X-Accel-Redirect or X-Sendfile under heavy load.

Next: Project: Public API Dashboard