HTML5 video player is becoming more and more popular day by day. Though it can stream with a given public video file URL, sometimes you will need to control the streaming from your server script to provide additional facilities like authentication, resume support, sending in partial chunks etc. In a recent project had such a use case, where a video needed to be streamed through PHP to the client browser’s HTML5 player. Here I will try to share my experience and code that will help you to implement PHP HTML5 video streaming easily and efficiently.
Checkout The PHP HTML5 Video Streaming Demo
The VideoStream class Code:
Following is a simple class, that includes all HTML5 streaming logic and is responsible for performing the main streaming action:
To use this class, you will have to write simple code like as below:
$stream = new VideoStream($filePath);
$stream->start();
Code language: PHP (php)
Understanding the class and HTML5 Streaming logic:
The class simply takes the path of the video file as a constructor parameter. It can either give it a local path, or even an amazon s3 file location as well(explained later).
after calling the ‘start()’ method, it first tries to open the file, then sets the proper headers, then streams the required contents and finally closes the file system handler.
The header part is the most important as here you will be communicating with the client browser, telling it that you can accept range requests and check if the browser made range requests or not and decide the amount of data to the stream. In the header setting, by default mp4 file’s mime type is given. You can change it according to your need. However, at this moment, mp4 is the most widely supported format across major browsers, so using this format is very much recommended. ‘Accept-Ranges’ header is important to tell the browser that the server is accepting any byte-level request in the given range, so that browser can decide the range itself and make custom range requests subsequently. When the browser makes a range request, it includes an additional header named ‘HTTP_RANGE’. Inside ‘setHeader()’ method, it just validates the range requests and decides how much data to send accordingly.
The ‘stream()’ method simply streams the predefined amount of data with a customizable buffer size. The buffer size is just to optimize the server memory utilization so that no huge memory is taken in case of a concurrent high number of requests.
Streaming From Amazon S3 Service:
You can have s3 service’s file location support on the above class very easily. First, make sure to register ‘streamWrapper’ with your s3 client:
$s3Client->registerStreamWrapper();
then, while passing the file path to VideoStream class’s constructor, use “s3://{bucket}/{key}” format as a file string. Then modify the class’s ‘open()’ method, as below:
/**
* Open stream
*/
private function open()
{
// Create a stream context to allow seeking
$context = stream_context_create(array(
's3' => array(
'seekable' => true
)
));
if (!($this->stream = fopen($this->path, 'rb', false, $context))) {
die('Could not open stream for reading');
}
}
Code language: PHP (php)
Now you should be fine and streaming should work from the Amazon S3 location as well.
Final Words:
Hope this small tutorial on PHP HTML5 Video Streaming will help you to get started with your next video streaming app. If you have any suggestions to improve the class, please suggest them by commenting. If you are having any trouble understanding any of the parts, feel free to ask as well. Happy coding 🙂
varshamane12345varsha says
Hi,
I am trying to play .mp3 files from amazon s3.. Unable to play 16 MB files from amaozon s3 using above code getting “GET http://192.168.1.253/php/test/index.php net::ERR_CONTENT_LENGTH_MISMATCH ” error ..Please suggest solution to resolve this..
Md Ali Ahsan Rana says
Hello,
Thanks for trying this video streaming tutorial! However, the link you gave isn’t working for me. Please use other sharing platform(dropbox/gist etc)
Alain says
Rana ,
Is it possible to show a part of the video
For exampe , a part from timstamp 1:15 to 2:15
thank you
Alain
Fadi Nasem Abu Alnaser says
thank you 😀
Manoj Milani says
It takes lots of time to load the video for the 1st time. I am playing 50 mb video file using the same code given above. Any thoughts?
Md Ali Ahsan Rana says
Did you compare the load time with direct media file loading and via PHP streaming(if so, give some link to test)? Also, it may depends whether you are streaming from S3, as such cases can cause slow loading as well(depending on bandwidth of your server and s3’s connectivity)
Samuel Than says
This tutorial is great !!..
I have a question. Does the this streaming takes up bandwidth of the local server or s3 itself ?
Md Ali Ahsan Rana says
I afraid, this will take both S3 and local server bandwidth, unless you cache the s3 on local machine. This is what I did in my case. First attempt to load video will be streamed directly from s3 and keep a backup on local machine. For consecutive requests, serve from local version.
Samuel Than says
I thought so. Thanks for the reply.
Felipe says
Hi! Thanks a lot for the tutorial.
Do you know how to make it loop?
vasilis says
Thank you for the article. How do you feed the stream to the player? Do you echo $stream->start(); to the src attribute of a HTML5 tag? thank you!
Md Ali Ahsan Rana says
@vasilis, no. You have to give the php script’s url in the src attribute of a HTML5 tag.
Kuzi says
Hi
Great article, I am also trying to stream to a player but the video is taking over my whole page how do i make the video is just added to my html5 player. Thanks
Derrick says
Put the streaming code ($stream = new VideoStream($filePath);
$stream->start();) in a separate php file eg stream.php , and then in a different php file put video tag and in the src attribute put stream.php ,
<video width="100%" height="500"
it will stream without taking the whole page.
Saheed says
Its not working
Rameleu says
Hello, I also tried to feed my HTML5 player with it, but it’s not working, and I don’t understand what you mean by “give the script url”, what should I input ? Thank you a lot !
vasilis says
Thanks a lot for the quick reply. I implemented the video streaming for two videos, one local in the server and one in S3. The local video plays well with all the browsers. The video I stream from S3 plays fine in Firefox and Safari but in Chrome I receive error net::ERR_CONTENT_LENGTH_MISMATCH in the middle of the video (similar to the one reported in the 1st message). However, Firefox seems not to use the Range HTTP header, unlike Chrome.
You can test the videos using the following links, the first streams the local video, the second streams the video from S3.
http://23.20.72.172/player/player.php
http://23.20.72.172/player/s3player.php
In the apache error log I get the following error:
“PHP Fatal error: Uncaught exception ‘Guzzle\\Common\\Exception\\RuntimeException’ with message ‘Cannot seek to byte 5382346 when the buffered stream contains only 0 bytes” for this line:
$context = stream_context_create(array(
‘s3’ => array(
‘seekable’ => true
)
));
Do you think it’s a bug in your code, chrome or S3?
Thanks a lot,
Vasilis
Md Ali Ahsan Rana says
Hello vasilis, I have checked your s3 player on my chrome and its working ok(on mac osx). So, I guess, its a problem from chrome browser from your side. So, I can suggest you to try checking this thread on this net::ERR_CONTENT_LENGTH_MISMATCH error if it can help solve your issue. Also, Feel free to share your experience, if you become successful to solve it, on this post by commenting so that other readers get help if they suffer from similar issue.
krishna says
Warning: fopen() [function.fopen]: Filename cannot be empty in G:\g\xampp\htdocs\strm.php on line 27
Could not open stream for reading….hi am new to php…and how to call $stream->start(); in video tag …and how we set the local video path….. thanks in advance
Md Ali Ahsan Rana says
Hello krishna, in video tag, you won’t be calling the ‘$stream->start()’ method. Rather you will give the url of the php file that calls that method. I already gave an example above. I have also updated the php video streaming demo page with code example. Hope these helps!
438sunil says
I to have the same doubt as krishna said…. plz will to explain with more clarity thanks!
vasilis says
Hi Ahsan, I was able to solve my problem by making the $buffer very small, only 512. Now it works fine although I’m not sure why, it looks specific to S3 stream wrapper. I’ll test it with more videos.
venky says
i’am trying to build a webapp to stream videos from client to rtmp server without uploading the file. is it possible ??
Ahmad says
I want to stream a live event from a camera, is it possible to stream it with the php script? can you explain How ?Thanks
Hùng Vũ says
very very thank you, my life saver
Bonny says
Good one. Had issue playing mp4 video but now is playing.
Bonny says
How can I use for uploading video files to my server. I want it to upload files in chunks. Any suggestion will be appreciated.
sujith says
Hi thanks a lot for your wonderful tutorial , I have question , what is difference between show the video directly through html5 video tag and through PHP code ? can you please explain ,is there any performance difference ?
Md Ali Ahsan Rana says
Performance is not the main fact here. Control is. Streaming it via a custom script, you can actually perform several useful features web app usually needs, such as authentication, control bandwidth, block requests that might be overading the server, analytics, support different media types on the fly etc….(list goes on).
John.G.Sujith says
thank you
omgsupport says
Hey John, I use this script for security reasons. My site (https://omgartists.com) allows musicians and bands to upload music files and host them. I use this solution because not all artists and bands want their music downloaded. Setting a URL to the HTML5 src tag allows the visitor to do that. I use this script to stream the audio to an HTML5 video tag. It doesn’t get saved in the cache, and can’t be downloaded directly.
sandro says
“It doesn’t get saved in the cache, and can’t be downloaded directly.” loool, really?
What about “right-mouse-button” and then “file save as…” in IE, Firefox, …
Gregory Robert Siler says
Yes, really…
My first question would be ‘right-click’ on what? In the case I’m describing, there is no object on the page to ‘right-click’ on. I’m not using a tag.
Also, if you view the network activity in your debugger, it will show something like ‘https://omgtap.co/audioplayer/streamAudio.php?7o5u57EX’ as the source of the audio stream.
Copying that link to a browser window will give the visitor an ‘Invalid Security Key’ warning because I have security set up so that it will only stream to a call from the page it’s embedded in.
So, yes… It does work.
Check out reverbnation.com, they do the same thing – you cannot save a song that’s streaming from their site. You can always ‘record’ the song as it’s streaming, but you cannot save the file directly.
1. Set your audio player’s SRC to a url that pulls the audio file URL on the server side (so that it’s not accessible in your code).
2. Set up security in your SRC url to only stream to the domain and page it comes from – this will keep the stream from working anywhere but where you want it to be pulled from.
3. Right click’s don’t work – there’s nothing to right-click.
4. The audio stream will NOT be saved in your cache and is not available to pull from a separate browser window.
Fred says
Hello I want the video to play on a div and not take the whole page , how can I?
Cristian says
thanks for that, saved me the hassle of writing it myself 😀
cheers
Jean-Loup says
Hello, Thanks for the class, it works almost perfectly ! However, I realized that the script from which I’m building the VideoStream object and executing start() is re-executed 2 or 3 times. Do you have the same issue or do you have any idea about how I can fix it?
Thanks for your help
Cheers
Chandu says
This is a very Informative and useful article. Thanks for sharing.
tirupathi says
Hi, I am using your script to play a video, when i play two files one by one in refresh, it is playing the old one only, some times even I eventually gave a video file it does not exist, it is playing the old one only. I think the ‘$stream = new VideoStream($file); object is not getting destroyed for the second time onwards. When I log off and login again, then the changed file(or second file) is played, but again if change to next file it is playing the previos on only. In my app user selects list of files to play but, only first time selected file only played always. What could be the reason. Thank you.
grafenberger says
Thanks for sharing. But I don’t really get why I should use this script and not simply embedd it with the HTML5 tag?
omgsupport says
I use the script on my site to hide the mp3 url so it cannot be downloaded without permission from the artist or band that uploaded it. Just placing the url of the file in the HTML5 tag allows the visitor to 1) right click on the HTML5 Video element (if being displayed) and download the source, or 2) find the source file in a browser network inspector and download it from the cache. Streaming with this method doesn’t leave the file in the cache. https://omgartists.com is my working model using this streaming script.
Dmitri Novikov says
Great! 100% working code, I only had to pass the correct path to my video ))) What a luck, thank you!
Tom says
Great work!
But i doesn’t run for files larger than 2GB.
Md Ali Ahsan Rana says
Its probably because you are trying it on a x86 system. You can try using solutions mentioned on this stack-overflow thread: http://stackoverflow.com/questions/5501451/php-x86-how-to-get-filesize-of-2gb-file-without-external-program
Magnani says
i need create a looping files….how to with this? thanks for helping!
prem says
Hello
Thanks a lot for the tutorial.
Do you know how to make it loop?
I want the video should always playing.
Currently its stop after its completed but i want that its play again automatically .
AcehPonti ITB SeamolecDuwan says
helloo,,
how to combine source code HTML5 video streaming with API REST Web services.
Thanks for you helping,…!
Raju Odedara says
Notice: Undefined variable: filePath in C:\xampp\htdocs\programs\live_stream.php on line 1
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\programs\live_stream.php on line 25
Could not open stream for reading
I just add your code into my page.It gives me above error notice & warning.Please help me.
for live streaming
Thiago says
Hello,
How do I add subtitles to the movie?
thanks
klcin, 0301-3482074 says
can u help me to be online my video streaming
Marko says
Thanks
It helped a lot
wasted lots of time to get partial content working!
HazCod says
Hi, just FYI, I slightly modified your VideoStream class to use stream_get_contents() and to force write/close the PHP session before starting streaming to evade some problems when navigating away.
https://github.com/HazCod/Gunther/blob/master/application/includes/VideoStream.php
Lo says
thanks, this tutorial is awesome!!
I have a question.If I want to prevent download by right click(or download file cannot be play), then how can I modify this code?
Nikola says
Great tutorial! However it works only in Chrome and not in Firefox (40.0.2) for me. The error is Video format or MIME type is not supported.
Samyadh Jain says
I feel this is very late but i am finding a strange issue, the video is working fine in local but when i upload in server it is not playing at all. i have checked the headers its all fine.
Do we have to alter server for playing files? if so then please let me know what all changes have to be done.
Thanks in advance
Dornadula V Umashankar says
Hi, I trying to develop video confrencing software with minimum 24 to maximum 50 users online to pull their IP addresses and video recording or chat support with file attachments like lync I need developers to support my email id: shankartvt@rediffmail.com
Akos says
You saved me a couple of hours! Thank you for posting this!
@HazCod: thanks for the modified version! Solved my “navigating away issue”.
Marcio says
Thanks. Really worked for me.
joseavilez says
You just make me recover my job with this awesome, perfect, great, fabulous Streaming Class! I love you soo much from the bottom of my soul. Hahaha Thanks!!
tungtrum17 says
Thanks! It working on FF and Chrome, but not working on Safari and devices all iOS. In case Stream for S3…
how to fix??
Thanks!
javaconfig says
Thanks! But not working on Safari! How to Fix This!
Hao says
The lession ‘s very good ! but onething….it works fine in Chrome & Firefox ….Safari & orther iOS devices not working ….so how can i fix that ?
rorenzo says
hi, did you fix for safari?
David Dick says
I have applied to my project. It works fine, but there’s a problem. On Safari does not work with stream s3.
Here are two link demo:
1: mp4 Streaming: https://shop.oohhay.com/demo/readfile
2: s3 Streaming: https://shop.oohhay.com/demo/s3readfile
I was doing something wrong, please help me!
person says
(Sorry for my English)
why you use HTTP and not RTP in this script, I know that for a streaming video we use RTP protocol, no?,
please I wait for your answer, I must use this script in my research work if it’s possible.
Ananthaselvam says
Hi Rana,
I need your help, how to find given url link is a video link in php.
ghassan abdu says
Warning: Cannot modify header information – headers already sent by (output started at C:\AppServ\www\streaming\home.php:1) in C:\AppServ\www\streaming\home.php on line 42
izzy says
hi, how can i save the session buffer and when the user refresh the page, the video starts at the last moment saved
azhar says
Hello, im just wondering is it possible if the video dimension to be changed for example to be 800X600?
Tony says
Hi there,
I needed to change
header(“Accept-Ranges: 0-“.$this->end);
to
“header(“Accept-Ranges: bytes”);
to get the seeking to work correctly. My web browser during testing was firefox.
Gofi says
thanks Rana, good stuff.
Bright says
I have used the code but its not working, now I have realized that I didn’t use this code => $stream = new VideoStream($filePath);
$stream->start();. Please tell me which page do I place it?
jonnyboy82 says
Nice tutorial, thank you. I wonder if you could take it a step further and explain how to ensure that the user could only be streaming 1 video at a time?
I have been using this code example for a few weeks and I have tried so many approaches and I have failed at every turn.
I would appreciate any guidance you could provide.
Thank you
Damn Nastro says
Hello Rana!
I am a complete beginner to Video Streaming lessons in PHP but I have learned basic php
I can just connect to database and insert data and display it how I like cut strings and explode functions but I need a complete tutorial on how to change header what is range for browser please can you give me some video type tutorial or tell me where I can find such tutorials or series of tutorials covered only for video streaming and header And I don’t know what header can actually do without header(“location:url”) so please helllllllllllllllllllllllllllllllllp;
iammuslimpakistani
Frankwin Hooglander says
How to use your class to grab the stream from an IP Camera so it can be wrapped in this class to make things like username/password and real camera IP not visible to the end-user. Things like filesize() don’t work for that.
Nick says
Dear Mr. Rana,
thank you for sharing this great piece of work. Most helpful was the demo, which, unlike to others, prooved your way does really work.
Best feature is that a file like “../../mydata/movie.mp4” will be streamed. This makes it possible to store the files where a normal URL cannot access it.
———————–
Some clarifying clues to other developers how to integrate this in your application:
Step 1) The page where you want to show your video is at minimum like this:
Untitled
Step 2) The used file movie_Rana.php goes like
<?php
include_once("RanaVideoStream.php"); // when include_path is set or else use require_once
$stream = new VideoStream("../../data/mymovies/mymovie.mp4" ); start();exit;
?>
Step 3) Copy the complete code from above (or the Gunther improvement) in a new file and name it
RanaVideoStream.php
Thats it. 🙂
Omkar Sagare says
Thanks nick…!
Nick says
It ate may code… Next try for Step 1:
Create an empty html-page. In the body only one line is needed, here echoed by php.
<?php
echo '’;
?>
Nick says
Sorry, cannot post code here.
In Step 1, use the video element and type src= movie_Rana.php with apostrophs
Agnibesh Mukherjee says
Awesome man! Thanks a lot. It works like a dream.
Ankit says
Hii, I am new for CodeIgniter then i want to know that how to use this files in CodeIgniter.
Youssef M'HAMDI says
Hi
Great article, I am also trying to stream to a player but the video is taking over my whole page how do i make the video is just added to my html5 player. Thanks
Vinicius Demetrio says
Hi Rana, i´am using your code and it works well (thanks 🙂 !!! ) when i test from my computer to smartphone (android and IOS). But, i´m using a solution of captive portal of a router with OpenWRT and i have limited resources. So, i have to play a video before allow the user login or create a profile, but the stream doesn´t work in this case. Do you know what it would be the problem ? ffmpeg ? php modules ? Could you give me some tip for this situation ?
Temujin Jumlani says
Thanks!
Works like a charm.
inanbayram says
Great script! It’s possible to stream more than one video file in a script?
I tried the following code and also delete the exit; lines but the script is just serving the first videofile and not the two files 🙁
$stream1 = new VideoStream($file1);
$stream1->start();
$stream2 = new VideoStream($file2);
$stream2->start();
inanbayram says
Hello,
it’s possible to stream 2 video files in 1 php script? I tried it but it’s streaming only the first video file. Of course I dele the lines with exit; command
Mohammad Hooshyar Ahmadi says
Hi and thanks a lot for your shairing
If we want stream a live but user can not save the video file. How can create the downloading limitation ?
Rahmat says
thanks your information
Peter Balla says
Thank you very much!!!
Aju says
Hi,
Thanks for a wonderful article.
I tried to use the method for stream on my site. It is on codeigniter. I added the videostream.php as a library and called as a library. But the video cannot play. It is showing error as the video file is corrupt. But the url I tried to play is correct and the file exist in the url. Please help me
Vikas says
I might have a silly Question but i need to ask that i need to use the webcam and save the video to my Amazon server and do want to put a security when playing back in other words i want user save his video from his webcam to websites amazon server and when he give the access to his friend to view the video he provide him password also so only authorized users can see the video do any one has any solution for the same
kamal says
I’m trying to access the video from AWS but the code seems not working to me. I think, I’m configuring it differently. Although it’s working good if video load from same directory. I need you help urgently, please look into the matter and help me out from this.
I’m getting confused how to use this “s3://{bucket}/{key}” string into the file path.
Here what I’m trying to configure
$credentials = array(
‘key’ => ‘AWS KEY’,
‘secret’ => ‘AWS Secret KEY’
);
// Instantiate the client.
$s3Client = new Aws\S3\S3Client([
‘version’ => ‘latest’,
‘region’ => ‘us-east-1’,
‘validate’ => [‘required’ => true],
‘http’ => [
‘verify’ => true
],
‘credentials’ => $credentials
]);
Now how to use “s3://{bucket}/{key}”?
Gandhi says
Hi i thank you for giving streaming fuctionality. Is there any way to delete original file from path after streaming
nicorobin says
hello
Great article, I’m trying to stream to player, I don’t want video autoplay. please help me thank.
Nilesh says
Hi,
I tried using this and is working perfectly fine. Issue comes here.
Video size is 600mb. Playing fine.
But while video is playing if user is clicking on any other link on site its now going to that page it simply playing the video and not going to other page.
What can be the issue?
Jorgw says
I’m having the same issue. Did you solved?
Alex says
Thank you for this excellent code. I noticed that some browsers such as the one listed at the bottom of this post set $_SERVER[‘HTTP_RANGE’] to something like [bytes: 0-65536] (without the brackets). To allow this code to work for those, I’ve modified line 53 in your example to:
if (strpos($_SERVER[‘HTTP_RANGE’], ‘=’) == false) {
// the name and value are delimited by a colon instead of an =
list(, $range) = explode(‘:’, $_SERVER[‘HTTP_RANGE’], 2);
} else {
// this handles most cases where the name and value are delimited by an =
list(, $range) = explode(‘=’, $_SERVER[‘HTTP_RANGE’], 2);
}
Mozilla/5.0 (Linux; Android 5.1.1; LGMS330 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.89 Mobile Safari/537.36
Ronald says
how do i insert the video directory path so i can access multiple videos on the html page?
atozexams says
What is the difference between buffer and stream?
Linh Kute says
Hello, Sir ?
Can you show me how to stream with cookie, thank you. I use to stream google drive
Lucifa says
I love you!
Was trying this about 1 week found million of tutorials some didn’t work with other browsers some couldn’t be downloaded yours is the best anything is working fine!
Thank you so much!
manoj says
I want to stream a live event from a camera, how is it possible to stream it with the php script? can you explain?Thanks
Giuliano says
with this library: can i stream a live video from a webcam? or only functions with a saved file? I want to show a billiard tournament for all my country or people in other cities.
neeraj says
how we can set start time. Like need to set 10 sec. so video will direct start from 10 sec completion of video
Saurabh says
Hi Can Anyone suggest me any company who can provide such API through which i can built website where my users can go live from their laptops or desktops with webcam?
Mik says
Can i feed in videos directly from IP camera?
Vikash Kumar says
I have used the video streaming code which you have mention in your website, but when i refresh the page again and again then video play from staring. This is not a live video streaming. I want to implement live video streaming in my website, can you please tell how to implement live video streaming?
Vipul Patel says
Hello Sir,
I am unable to streaming with s3 bucket.
I config all thing as per your guidance.
Please help me.
swapnil says
Hi Md Ali Ahsan Rana,
Nice tutorial. This is help full for us. I have use for mp3 its working. Now I am working on downloading more than 2gb zip file from PHP. Scenario is that we have zip file located in CDN azure. and I am trying to download this big size of file from my azure server using PHP. its working for 1megabyte then it is aromatically exit. it is not working for big size more than 2gb of file. I have modified your code like file size which is getting from header ($headers[‘Content-Length’] –> get_headers($filename , 1)) and buffer size. I am trying to debug and update while loop, but not getting success. Can you please assist me on this scenario. This will help me a lot.
Sorry, I am hiding my website name
Thanks,
Swapnil
Swapnil Shete says
Hi,
This is a swapnil. I have commented on this blog related large zip (< 2 gb) file, few days ago. I really appropriate if you help me out. I tried this code with large zip file. it is terminated my script. I have set memory limit , script execution time in script but does not execute. can you please assist me on this scenario.
Thanks,
Swapnil
Meer says
Please Let Me Know How to embed web camera / ip camera instead of video file to make this project work as live streaming. (like an event is streamed over ip)., Please reply as soon as possible, Make me back that will be your most kindness at : softivasolutions@gmail.com
Durga Pratap says
include “./libraries/VideoStream.php”;
$stream = new VideoStream(“my folder path”);
‘
$stream->start();exit;
But sir how to implement in video frame.
Durga Pratap says
And how to implement in website.
Yanming Wei says
$stream->start() plays video immediately, but I wish it in standby state, i.e. PAUSE, and wait for clicking “play” button.
How to code it?
thanks
sejpalsinh jadeja says
Can please any one explain me where all code i have to put ??
Soma Satyanarayana says
how to eliminate download option
Chris says
Dear Rana,
thank you for code & tutorial. Works fine in Firefox&Chrome, but Safari has difficulties with the range I guess. With every chunk the browser is loading a large part of the full file. My source file is 154mb, but after 7min of video, safari has loaded 1.31gb of data within 85 requests to the video file.
This is an example header of a 108mb chunk:
Anfrage
Accept: */*
Range: bytes=40763392-154802295
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15
Referer: http://127.0.0.1/xxx/yalac_test/
Accept-Encoding: identity
Connection: Keep-Alive
X-Playback-Session-Id: EA87F6BE-4EC3-4F72-A757-89CEE52C86AE
Antwort
Content-Type: video/mp4
Keep-Alive: timeout=5, max=100
Expires: Wed, 13 Nov 2019 07:41:53 GMT
Referrer-Policy: unsafe-url
Cache-Control: max-age=2592000, public
Date: Mon, 14 Oct 2019 07:41:53 GMT
Content-Length: 114038904
Connection: Keep-Alive
Accept-Ranges: 0-154802295
Content-Range: bytes 40763392-154802295/154802296
Last-Modified: Fri, 11 Oct 2019 06:09:20 GMT
X-Powered-By: PHP/7.1.23
Server: Apache/2.4.34 (Unix) PHP/7.1.23
Any idea what is going wrong?
Will build a test site and send the URL in case you are willing to have a look at it?
Regards, Chris
Rick says
Nice class and thank you for sharing.
I serve multiple video files types being served, so wanted to set the correct mime-type in the header.
I added the following to the class properties
private $ext = “mkv”;
private $mimeType = “video/x-matroska”;
private $MIMETYPES = [
‘mkv’=>”video/x-matroska”,
‘webm’=>”video/webm”,
‘mp4’=>”video/mp4″,
‘3gp’=>”3gpp”,
‘flv’=>”x-flv”,
‘ts’=>”video/MP2T”,
‘avi’=>”video/x-msvideo”,
‘wmv’=>”video/x-ms-wmv”
];
Added these lines to __construct function
$this->ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$this->mimeType = $MINETYPES[$this->ext];
Changed setHeader function
Replaced
header(“Content-Type: video/mp4”)
with
header(“Content-Type: ” . $this->mimeType);
Louis Mefor says
Hi RIck i have tried this, but my code isnt working, i just get a blank page, you have any idea? my email is mefor.louis@gmail.com please can you send me your source code?
Nick says
Type-error in $this->mimeType = $MINETYPES[$this->ext]; MIME instead of MINE .
Daniel says
Nice code, I’ve tried it with local files but I’ve got no luck in getting this to work with files over ftp, any ideas?
Rana Ghosh says
I have tried this using S3 bucket video file. But not working. According to my finding feof() function is not working properly. Any clue?
Appreciate your help.
manishpanchal says
its not supprted on safari browser.
Can u help me how to stream video on safari browser ?
intolap says
$buffer variable is never used in the script.
So, how does it affect the streaming?
Also $buffer = 102400, what is this bytes or kbytes?
TAKONDWA says
Am falling to connect to with html, help me with HTML code
iswaps says
Hello All,
I have implemented the code but having below issues.
filesize(): stat failed for {{full path}}
I have tried using same path in direct in URL and it’s working same. Also, without stream everything working fine… please guide me.
S. Chalisque says
I think line 59 should read
if ($range[0] == ‘-‘) {
note the [0] so as to check that the first char is “-“, rather than the whole string.
Daruma says
Hello. Greet class. But how protect file? (hotlink)
zasrin says
Hey! Greet Class! Please help. How to protect video file? (hotlink).
i use ngnix. valid_referers not working. 🙁
Dereck says
Thank you, I like using php. It’s hard to find up-to-date resources, but this still works!!
Denis says
This is great.
I have a question. Perhaps you can help.
Any idea how’s the javascript client would look like?
i want to transfer to via an AjaxRequest instead of the video player.
Any hint, clues, examples, what should I look for, would greatly help.
I’ve tried searching transfer binary file
It’s not clear to me how to compose the XMLHttpRequest.
Abdullah Nurum says
I’m using godaddy for server, and this php code returning perfect api. but how do I read this api returned response to video? where is JavaScript part? I am using angular for front end.
Micilini says
Your code needs some UPDATES, the VideoStream Class dont have ability to read and stream EXTERNAL VIDEOS (only local files). To solve this problem, I create a package that works with external video files 😀
Check it out: https://github.com/micilini/video-stream
Ryahu Gmikyu says
yeah its work
with php we can protect video
but php as video is not practical
sure if you have 1-2 video with dozen viewer, it will be fine
but if you want make streaming site, you will need ten thousand dollar to keep up your hosting
better to use third party streaming site again yt, bili, etc