Created
April 16, 2014 17:06
-
-
Save sarciszewski/10908080 to your computer and use it in GitHub Desktop.
Serve and Destroy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$file_dir = "/home/scott/public"; // Change this | |
$destroy = true; // TRUE: unlink; FALSE: chmod -r | |
/** | |
* Add this to your nginx server block: | |
rewrite ^/download/(.*)$ /serve_and_destroy.php?file=$1; | |
**/ | |
function get_file_extension($path) { | |
$split = explode('.', strtolower($path)); | |
return $split[count($split) - 1]; | |
} | |
function get_filetype($path, $ignore_ext_fallback = false) { | |
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); | |
$filetype = finfo_file($finfo, $path); | |
finfo_close($finfo); | |
if(!$ignore_ext_fallback) { | |
if(preg_match('/^application\/octet-stream/', $filetype)) { | |
// This is usually the result when you query a file that was just uploaded | |
$ext = get_file_extension(strtolower($path)); | |
switch($ext) { | |
case 'jpg': | |
case 'jpeg': | |
$filetype = 'image/jpeg'; | |
break; | |
case 'png': | |
$filetype = 'image/png'; | |
break; | |
case 'gif': | |
$filetype = 'image/gif'; | |
break; | |
case 'pdf': | |
$filetype = 'application/pdf'; | |
break; | |
case 'zip': | |
$filetype = 'application/zip'; | |
break; | |
// Add any other special cases here if you really want | |
} | |
} | |
} | |
return $filetype; | |
} | |
if(empty($_GET['file'])) { | |
die("404"); | |
} | |
$path = preg_replace('/[^\x20-\x7e]/', '', $file_dir . '/' . $_GET['file']); | |
if(!preg_match("/^".preg_quote( preg_replace('/([^\\])\//', '$1\\/', $file_dir) )."/", basename($path) )) { | |
die("Directory transversal not allowed"); | |
} | |
if(!is_readable($path)) { | |
die("404"); | |
} | |
header("Content-Type: ".get_filetype($path)); | |
echo file_get_contents($path); | |
if($destroy) { | |
unlink($file); | |
} else { | |
chmod($file, 0400); // Do not let us read it | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment