Last active
August 29, 2015 14:06
-
-
Save michael34435/9ba150a3bf41fa1e593e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
function download($path, $name, $range = null) | |
{ | |
if (!file_exists($path)) { | |
header("HTTP/1.1 404 Not Found"); | |
exit(); | |
} | |
header("Pragma: public"); | |
header("Expires: -1"); | |
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); | |
header("Content-Type: application/octet-stream"); | |
header("Content-Disposition: attachment; filename='{$name}'"); | |
header("Accept-Ranges: bytes"); | |
if (!empty($range)) { | |
list($size_unit, $range_orig) = explode('=', $range, 2); | |
if ($size_unit == "bytes") { | |
list($range, $extra_ranges) = explode(',', $range_orig, 2); | |
} else { | |
$range = ""; | |
header('HTTP/1.1 416 Requested Range Not Satisfiable'); | |
exit(); | |
} | |
} else { | |
$range = ""; | |
} | |
$file_size = filesize($path); | |
list($seek_start, $seek_end) = explode('-', $range, 2); | |
$seek_end = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)), ($file_size - 1)); | |
$seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)), 0); | |
if ($seek_start > 0 || $seek_end < ($file_size - 1)) { | |
header("HTTP/1.1 206 Partial Content"); | |
header("Content-Range: bytes {$seek_start}-{$seek_end}/{$file_size}"); | |
header("Content-Length: ".($seek_end - $seek_start + 1)); | |
} else { | |
header("Content-Length: {$file_size}"); | |
} | |
$fd = fopen($path, "rb"); | |
fseek($fd, $seek_start); | |
while(!feof($fd)) { | |
echo fread($fd, 4096); | |
ob_flush(); | |
if (connection_status() != 0) { | |
@fclose($fd); | |
exit; | |
} | |
} | |
fclose($fd); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment