Skip to content

Instantly share code, notes, and snippets.

@syntaxseed
Created October 21, 2021 15:09
Show Gist options
  • Save syntaxseed/5bee801b801e5af6bf01d0337c657da7 to your computer and use it in GitHub Desktop.
Save syntaxseed/5bee801b801e5af6bf01d0337c657da7 to your computer and use it in GitHub Desktop.
PHP: Fetch files from above the web root.
<?php
/******************************************************************
* This script will stream files that are stored above the web root.
* Public domain. Author: Sherri Wheeler. SyntaxSeed.com.
* Provided "as is" with no warranty.
*******************************************************************/
// CHECK FOR MEMBER LOGGED IN HERE, or include this into a file
// which already checks for member logged in.
// ****** Array of Private Files*******
$privateFilesPath[1] = "/home/username/privatedocs/file1.doc";
$privateFilesName[1] = "file1.doc";
$privateFilesMime[1] = "application/msword";
$privateFilesPath[2] ="/home/username/privatedocs/file2.txt";
$privateFilesName[2] = "file2.txt";
$privateFilesMime[2] = "text/plain";
// *************************
$index = intval($_GET['id']);
if(array_key_exists($index, $privateFilesPath)){
$filepath = $privateFilesPath[$index];
header('Content-Description: File Transfer');
header("Content-type: ".$privateFilesMime[$index]);
header("Content-Disposition: attachment; filename=".$privateFilesName[$index]);
header("Content-Length: " . filesize($filepath));
header("Cache-Control: private"); // Required for IE6 opening PDFs.
if(ob_get_length()){
ob_clean();
}
flush();
readfile($filepath);
}else{
echo("File Not Found.");
}
exit(); // Remove this if including this script into another file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment