Skip to content

Instantly share code, notes, and snippets.

@piperone
Forked from m4tthumphrey/streamed.php
Created July 23, 2017 16:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save piperone/fc55c341cc0ad2eb8318439c7a19a7a8 to your computer and use it in GitHub Desktop.
Laravel response macro for streamed responses with seeking support
<?php
Response::macro('streamed', function($type, $size, $name, $callback) {
$start = 0;
$length = $size;
$status = 200;
$headers = [
'Content-Type' => $type,
'Content-Length' => $size,
'Accept-Ranges' => 'bytes'
];
if (false !== $range = Request::server('HTTP_RANGE', false)) {
list($param, $range) = explode('=', $range);
if (strtolower(trim($param)) !== 'bytes') {
header('HTTP/1.1 400 Invalid Request');
exit;
}
list($from, $to) = explode('-', $range);
if ($from === '') {
$end = $size - 1;
$start = $end - intval($from);
} elseif ($to === '') {
$start = intval($from);
$end = $size - 1;
} else {
$start = intval($from);
$end = intval($to);
}
$length = $end - $start + 1;
$status = 206;
$headers['Content-Range'] = sprintf('bytes %d-%d/%d', $start, $end, $size);
}
return Response::stream(function() use ($start, $length, $callback) {
call_user_func($callback, $start, $length);
}, $status, $headers);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment