Created
August 3, 2021 19:13
-
-
Save Patrikgrinsvall/beaec150c7a55930d151edbb8de1a296 to your computer and use it in GitHub Desktop.
php function for http requests without dependencies
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
$path = "/absolute_path_to_your_files/"; // change the path to fit your websites document structure | |
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation | |
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters | |
$fullPath = $path.$dl_file; | |
if ($fd = fopen ($fullPath, "r")) { | |
$fsize = filesize($fullPath); | |
$path_parts = pathinfo($fullPath); | |
$ext = strtolower($path_parts["extension"]); | |
switch ($ext) { | |
case "pdf": | |
header("Content-type: application/pdf"); | |
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download | |
break; | |
// add here more headers if you use other content types | |
default; | |
header("Content-type: application/octet-stream"); | |
header("Content-Disposition: filename=\"".$path_parts["basename"]."\""); | |
break; | |
} | |
header("Content-length: $fsize"); | |
header("Cache-control: private"); //use this to open files directly | |
while(!feof($fd)) { | |
$buffer = fread($fd, 2048); | |
echo $buffer; | |
} | |
} | |
fclose ($fd); | |
exit; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment