Skip to content

Instantly share code, notes, and snippets.

@Artem-Schander
Last active July 14, 2017 07:14
Show Gist options
  • Save Artem-Schander/ae7ade19f9f18eab82189bee28f02009 to your computer and use it in GitHub Desktop.
Save Artem-Schander/ae7ade19f9f18eab82189bee28f02009 to your computer and use it in GitHub Desktop.
Get files from folders out of public access and pass them to the browser
/**
* @param string $fileName
* @param string $mime
* @param bool $download
* @param string $path
* @return mixed
*/
function fileProxy($fileName, $mime = 'auto', $download = false, $path = '/some/folder/')
{
if (basename($fileName) != $fileName) {
return 'Filename not valid!';
}
$path = substr($path, -1) == '/' ? $path : $path . '/';
$file = $path . $fileName;
if (!(file_exists($file) && is_readable($file))) {
return 'The file "' . $fileName . '" could not be found!';
}
if ($mime === 'auto') {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file);
finfo_close($finfo);
}
ob_clean();
if ($download === false) {
header('Content-type: ' . $mime);
header('Content-length: ' . filesize($file));
$open = @fopen($file, 'rb');
if ($open) {
fpassthru($open);
exit;
}
} else {
// download
$pathParts = pathinfo($file);
header('Content-Disposition: attachment; filename="' . $pathParts["basename"] . '"');
header('Content-type: application/octet-stream');
header('Content-length: ' . filesize($file));
header('Content-Disposition: filename="' . $pathParts["basename"] . '"');
header('Cache-control: private'); // open files directly
readfile($file);
die;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment