Skip to content

Instantly share code, notes, and snippets.

@stmllr
Last active February 17, 2023 06:41
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stmllr/5875566 to your computer and use it in GitHub Desktop.
Save stmllr/5875566 to your computer and use it in GitHub Desktop.
PHP script to download a file from files/ directory. Warning: no authorization or security checks implemented.
<?php
// You need to create the files/ directory inside your document root to put your files.
if (substr($_SERVER['REQUEST_URI'], 0, 7) !== '/files/') {
die('not allowed');
}
$absolutePath = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
$pathParts = pathinfo($absolutePath);
$fileName = $pathParts['basename'];
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$fileType = finfo_file($fileInfo, $absolutePath);
finfo_close($fileInfo);
$fileSize = filesize($absolutePath);
header('Content-Length: ' . $fileSize);
header('Content-Type: ' . $fileType);
header('Content-Disposition: attachment; filename=' . $fileName);
ob_clean();
flush();
readfile($absolutePath);
exit;
?>
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/files/.*$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f
RewriteRule ^(.*)$ index.php [L]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment