Skip to content

Instantly share code, notes, and snippets.

@psdtohtml5
Created May 24, 2013 22:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save psdtohtml5/5646810 to your computer and use it in GitHub Desktop.
Save psdtohtml5/5646810 to your computer and use it in GitHub Desktop.
PHP: Secure File Download
<?php
// PHP SECURE FILE DOWNLOAD
// Put the Files in a directory that is not publically accessible.. maybe outside document root or set correct permissions
if (!$_SESSION["authenticated"]) {
// If not authenticated then send back to the login page
$host = $_SERVER["HTTP_HOST"];
$path = rtrim(dirname($_SERVER["PHP_SELF"]), "/\\");
header("Location: http://$host$path/login.php?err=true");
exit;
}
$file = '/path/to/file/outside/www/secret.pdf';
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment