Support the ongoing development of Laravel.io →
posted 9 years ago
Requests
Last updated 1 year ago.
0

I'll answer my own post here. Managed to get it working after some tinkering. This is quite a dirty solution, as it always sends from the requested position to the end of the file (although no browser I've tried so far tries to set the range end to anything but the end of the file), doesn't respect ranges other than bytes, and so on.. Also just freshly copied from my test file, could probably use a lot of cleanup. But it least it works for seeking in 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);
	}

Then in the controller simply call something like

	return $this->streamFile("video/mp4", $path_to_file);

Hope it can help someone else looking for the same thing! By the way, some function like this would be a welcome addition to the Response class.

EDIT: Updated function with a small bugfix, sorry for bumping.

Last updated 1 year ago.
0

Thanks a ton! @ErikEklund you saved me lot of time.

But now I am having problem.My request header Range is always null.

I can play small videos.

But having problem with large videos.

Last updated 1 year ago.
0

Glad it can be of use to someone else :)

I have only tried this with video files on my site that are always in the 15-25Mb range, and it seems to work great for that at least. What size files are you using when it breaks?

Last updated 1 year ago.
0

thank man !

Last updated 1 year ago.
0

For those interested in the topic of working with media, I suggest to google "smartReadFile".

0

Can you please Tell me how to return. A view that includes the video response

0

Sign in to participate in this thread!

Eventy

Your banner here too?

ErikEklund erikeklund Joined 14 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.