Force downloading a file with PHP

A simple script to force a file download with PHP

With this script, it will be possible to force the download of a file with PHP, it is code to be customised with the valorisation of the $path and $name variables. Its purpose is to set up (force) the direct download of a file without making the absolute address of the file public.

The values of path and name can be enhanced by a reading from the db, in relation to an ID that we are going to supply in GET mode.

<?php

$path = "indirizzo/del/file/";
$name = "nomedelfile.ext";
$size = filesize($path); //calculate file size

header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Cache-Control: private');
header('Pragma: no-cache');
header("Content-Transfer-Encoding: binary");
header("Content-type: {$path['mime']}");
header("Content-length: {$size}");
header("Content-disposition: attachment; filename=\"{$name}\"");
readfile($path);
exit;

?>

We periodically check the functioning of the links in our articles. If you notice any links that do not work, please let us know in the comments. If you enjoyed the article consider supporting the blog with a small donation. Thank you. Patreon / Ko-fi / Liberapay / Paypal

Leave a Reply

Your email address will not be published. Required fields are marked *