Created
March 14, 2020 14:10
-
-
Save valmayaki/1a4c4ff1ebe33c0e8fd21b800e0fa237 to your computer and use it in GitHub Desktop.
Handling Http Range header in Laravel
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 | |
// https://laravel.io/forum/09-23-2014-how-to-support-http-byte-serving-in-file-streams | |
// Provide a streaming file with support for scrubbing | |
private function streamFile( $contentType, $path ) { | |
$fullsize = filesize($path); | |
$size = $fullsize; | |
$stream = fopen($path, "r"); | |
$response_code = 200; | |
$headers = array("Content-type" => $contentType); | |
// Check for request for part of the stream | |
$range = Request::header('Range'); | |
if($range != null) { | |
$eqPos = strpos($range, "="); | |
$toPos = strpos($range, "-"); | |
$unit = substr($range, 0, $eqPos); | |
$start = intval(substr($range, $eqPos+1, $toPos)); | |
$success = fseek($stream, $start); | |
if($success == 0) { | |
$size = $fullsize - $start; | |
$response_code = 206; | |
$headers["Accept-Ranges"] = $unit; | |
$headers["Content-Range"] = $unit . " " . $start . "-" . ($fullsize-1) . "/" . $fullsize; | |
} | |
} | |
$headers["Content-Length"] = $size; | |
return Response::stream(function () use ($stream) { | |
fpassthru($stream); | |
}, $response_code, $headers); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment