Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to send a file as a download

Short answer

Send the headers and output the file with readfile():

<?php
 
// download.php
 
$file = __DIR__ . '/files/report.pdf';
 
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="report.pdf"');
header('Content-Length: ' . filesize($file));
 
readfile($file);
exit;

A file name from the request

Never put a name from the address straight into the path: a ?file=../config.php request would hand out someone else's file. basename() drops the path and keeps only the name:

<?php
 
// download.php
 
$name = basename($_GET['file'] ?? '');
$file = __DIR__ . '/files/' . $name;
 
if ($name === '' || !is_file($file)) {
    http_response_code(404);
    exit('File not found');
}

Functions used in this recipe

  • readfile — Outputs the contents of a file.
  • header — Sends an HTTP response header.
  • filesize — Returns the size of a file in bytes.

Thanks for reading!

Donate to the site — we work hard for you.