Skip to content

Instantly share code, notes, and snippets.

@MasterEx
Created August 10, 2011 02:04
Show Gist options
  • Save MasterEx/1135904 to your computer and use it in GitHub Desktop.
Save MasterEx/1135904 to your computer and use it in GitHub Desktop.
PHP download file wrapper

In the example the directory that contains the script also contains the directory files.

In order to download a file with filename "file.txt" we should call the script like http://domainname/file.php?filename=file.txt .

If the file doesn't exist we will get a "FILE NOT FOUND" message, otherwise we will get the file.

This is a good practice in order to conceal our file true location.

<?php
$relativepath = "files";
if(isset($_GET['filename']))
{
$filename = $_GET['filename'];
$file = $relativepath."/".$filename;
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
else {
echo "FILE NOT FOUND! :(";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment