• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / PHP HTML5 Video Streaming Tutorial

PHP HTML5 Video Streaming Tutorial

March 24, 2014 by Rana Ahsan 134 Comments

video-streaming

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: html5, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. varshamane12345varsha says

    March 31, 2014 at 9:11 am

    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..

    Reply
    • Md Ali Ahsan Rana says

      April 1, 2014 at 5:28 pm

      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)

      Reply
      • Alain says

        September 13, 2019 at 4:26 am

        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

        Reply
  2. Fadi Nasem Abu Alnaser says

    June 3, 2014 at 3:42 am

    thank you 😀

    Reply
  3. Manoj Milani says

    July 14, 2014 at 3:45 am

    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?

    Reply
    • Md Ali Ahsan Rana says

      July 14, 2014 at 12:13 pm

      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)

      Reply
  4. Samuel Than says

    July 16, 2014 at 8:27 am

    This tutorial is great !!..
    I have a question. Does the this streaming takes up bandwidth of the local server or s3 itself ?

    Reply
    • Md Ali Ahsan Rana says

      July 16, 2014 at 7:06 pm

      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.

      Reply
      • Samuel Than says

        July 17, 2014 at 6:47 am

        I thought so. Thanks for the reply.

        Reply
  5. Felipe says

    August 27, 2014 at 11:57 am

    Hi! Thanks a lot for the tutorial.
    Do you know how to make it loop?

    Reply
  6. vasilis says

    September 3, 2014 at 1:27 am

    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!

    Reply
    • Md Ali Ahsan Rana says

      September 3, 2014 at 5:01 pm

      @vasilis, no. You have to give the php script’s url in the src attribute of a HTML5 tag.

      Reply
      • Kuzi says

        January 25, 2016 at 9:28 am

        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

        Reply
        • Derrick says

          June 22, 2017 at 10:08 pm

          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.

          Reply
          • Saheed says

            September 29, 2018 at 6:49 pm

            Its not working

      • Rameleu says

        June 19, 2017 at 8:25 am

        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 !

        Reply
  7. vasilis says

    September 3, 2014 at 9:34 pm

    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

    Reply
    • Md Ali Ahsan Rana says

      September 3, 2014 at 11:56 pm

      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.

      Reply
  8. krishna says

    September 4, 2014 at 7:41 am

    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

    Reply
    • Md Ali Ahsan Rana says

      September 4, 2014 at 8:38 pm

      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!

      Reply
    • 438sunil says

      October 27, 2014 at 6:28 am

      I to have the same doubt as krishna said…. plz will to explain with more clarity thanks!

      Reply
  9. vasilis says

    September 5, 2014 at 5:22 pm

    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.

    Reply
  10. venky says

    October 27, 2014 at 2:10 am

    i’am trying to build a webapp to stream videos from client to rtmp server without uploading the file. is it possible ??

    Reply
  11. Ahmad says

    November 2, 2014 at 2:14 am

    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

    Reply
  12. Hùng Vũ says

    November 12, 2014 at 3:13 am

    very very thank you, my life saver

    Reply
  13. Bonny says

    January 4, 2015 at 1:18 am

    Good one. Had issue playing mp4 video but now is playing.

    Reply
  14. Bonny says

    January 5, 2015 at 9:39 am

    How can I use for uploading video files to my server. I want it to upload files in chunks. Any suggestion will be appreciated.

    Reply
  15. sujith says

    January 23, 2015 at 5:30 pm

    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 ?

    Reply
    • Md Ali Ahsan Rana says

      January 28, 2015 at 4:11 pm

      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).

      Reply
      • John.G.Sujith says

        January 28, 2015 at 7:18 pm

        thank you

        Reply
    • omgsupport says

      October 2, 2015 at 11:58 pm

      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.

      Reply
      • sandro says

        April 7, 2016 at 6:40 am

        “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, …

        Reply
        • Gregory Robert Siler says

          April 10, 2016 at 3:07 pm

          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.

          Reply
  16. Fred says

    February 17, 2015 at 4:18 pm

    Hello I want the video to play on a div and not take the whole page , how can I?

    Reply
  17. Cristian says

    March 10, 2015 at 2:48 am

    thanks for that, saved me the hassle of writing it myself 😀
    cheers

    Reply
  18. Jean-Loup says

    March 10, 2015 at 5:52 pm

    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

    Reply
  19. Chandu says

    March 18, 2015 at 3:30 am

    This is a very Informative and useful article. Thanks for sharing.

    Reply
  20. tirupathi says

    April 3, 2015 at 5:15 am

    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.

    Reply
  21. grafenberger says

    April 11, 2015 at 9:48 am

    Thanks for sharing. But I don’t really get why I should use this script and not simply embedd it with the HTML5 tag?

    Reply
    • omgsupport says

      October 2, 2015 at 11:52 pm

      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.

      Reply
  22. Dmitri Novikov says

    April 17, 2015 at 2:28 am

    Great! 100% working code, I only had to pass the correct path to my video ))) What a luck, thank you!

    Reply
  23. Tom says

    May 1, 2015 at 5:11 am

    Great work!
    But i doesn’t run for files larger than 2GB.

    Reply
    • Md Ali Ahsan Rana says

      May 1, 2015 at 12:45 pm

      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

      Reply
  24. Magnani says

    June 24, 2015 at 9:37 am

    i need create a looping files….how to with this? thanks for helping!

    Reply
    • prem says

      February 4, 2019 at 2:39 am

      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 .

      Reply
  25. AcehPonti ITB SeamolecDuwan says

    June 25, 2015 at 12:19 am

    helloo,,
    how to combine source code HTML5 video streaming with API REST Web services.
    Thanks for you helping,…!

    Reply
  26. Raju Odedara says

    June 25, 2015 at 12:49 am

    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

    Reply
  27. Thiago says

    July 7, 2015 at 7:42 am

    Hello,

    How do I add subtitles to the movie?

    thanks

    Reply
  28. klcin, 0301-3482074 says

    July 11, 2015 at 11:32 am

    can u help me to be online my video streaming

    Reply
  29. Marko says

    July 21, 2015 at 8:09 am

    Thanks

    It helped a lot

    wasted lots of time to get partial content working!

    Reply
  30. HazCod says

    July 22, 2015 at 4:55 am

    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

    Reply
  31. Lo says

    July 25, 2015 at 1:11 pm

    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?

    Reply
  32. Nikola says

    August 21, 2015 at 4:42 pm

    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.

    Reply
  33. Samyadh Jain says

    August 25, 2015 at 8:19 am

    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

    Reply
  34. Dornadula V Umashankar says

    September 21, 2015 at 2:19 am

    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

    Reply
  35. Akos says

    September 24, 2015 at 4:38 pm

    You saved me a couple of hours! Thank you for posting this!

    @HazCod: thanks for the modified version! Solved my “navigating away issue”.

    Reply
  36. Marcio says

    October 2, 2015 at 12:28 pm

    Thanks. Really worked for me.

    Reply
  37. joseavilez says

    October 5, 2015 at 3:09 pm

    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!!

    Reply
  38. tungtrum17 says

    October 8, 2015 at 11:39 pm

    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!

    Reply
  39. javaconfig says

    October 9, 2015 at 12:07 am

    Thanks! But not working on Safari! How to Fix This!

    Reply
  40. Hao says

    October 9, 2015 at 1:56 am

    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 ?

    Reply
    • rorenzo says

      December 17, 2020 at 6:16 am

      hi, did you fix for safari?

      Reply
  41. David Dick says

    October 9, 2015 at 2:54 am

    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!

    Reply
  42. person says

    October 12, 2015 at 5:20 pm

    (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.

    Reply
  43. Ananthaselvam says

    October 30, 2015 at 4:29 am

    Hi Rana,
    I need your help, how to find given url link is a video link in php.

    Reply
  44. ghassan abdu says

    November 6, 2015 at 10:24 am

    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

    Reply
  45. izzy says

    November 19, 2015 at 10:44 am

    hi, how can i save the session buffer and when the user refresh the page, the video starts at the last moment saved

    Reply
  46. azhar says

    November 30, 2015 at 2:28 pm

    Hello, im just wondering is it possible if the video dimension to be changed for example to be 800X600?

    Reply
  47. Tony says

    December 15, 2015 at 12:50 am

    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.

    Reply
  48. Gofi says

    January 25, 2016 at 12:28 pm

    thanks Rana, good stuff.

    Reply
  49. Bright says

    January 27, 2016 at 8:25 am

    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?

    Reply
  50. jonnyboy82 says

    March 28, 2016 at 3:55 am

    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

    Reply
  51. Damn Nastro says

    April 3, 2016 at 5:33 am

    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

    Reply
  52. Frankwin Hooglander says

    May 4, 2016 at 2:39 pm

    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.

    Reply
  53. Nick says

    May 27, 2016 at 3:35 am

    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. 🙂

    Reply
    • Omkar Sagare says

      November 1, 2016 at 2:03 am

      Thanks nick…!

      Reply
  54. Nick says

    May 27, 2016 at 3:44 am

    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 '’;

    ?>

    Reply
    • Nick says

      May 27, 2016 at 3:58 am

      Sorry, cannot post code here.

      In Step 1, use the video element and type src= movie_Rana.php with apostrophs

      Reply
  55. Agnibesh Mukherjee says

    June 10, 2016 at 8:01 am

    Awesome man! Thanks a lot. It works like a dream.

    Reply
  56. Ankit says

    June 30, 2016 at 12:25 am

    Hii, I am new for CodeIgniter then i want to know that how to use this files in CodeIgniter.

    Reply
  57. Youssef M'HAMDI says

    July 28, 2016 at 3:31 am

    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

    Reply
  58. Vinicius Demetrio says

    August 12, 2016 at 12:40 am

    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 ?

    Reply
  59. Temujin Jumlani says

    September 2, 2016 at 5:00 pm

    Thanks!

    Works like a charm.

    Reply
  60. inanbayram says

    September 6, 2016 at 6:10 pm

    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();

    Reply
  61. inanbayram says

    September 12, 2016 at 6:58 am

    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

    Reply
  62. Mohammad Hooshyar Ahmadi says

    October 3, 2016 at 4:07 am

    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 ?

    Reply
  63. Rahmat says

    November 17, 2016 at 10:37 am

    thanks your information

    Reply
  64. Peter Balla says

    December 4, 2016 at 3:25 pm

    Thank you very much!!!

    Reply
  65. Aju says

    December 15, 2016 at 12:48 am

    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

    Reply
  66. Vikas says

    December 24, 2016 at 12:04 am

    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

    Reply
  67. kamal says

    December 27, 2016 at 8:02 am

    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}”?

    Reply
  68. Gandhi says

    January 3, 2017 at 11:35 pm

    Hi i thank you for giving streaming fuctionality. Is there any way to delete original file from path after streaming

    Reply
  69. nicorobin says

    January 8, 2017 at 9:58 pm

    hello

    Great article, I’m trying to stream to player, I don’t want video autoplay. please help me thank.

    Reply
  70. Nilesh says

    April 17, 2017 at 7:46 am

    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?

    Reply
    • Jorgw says

      June 27, 2017 at 9:10 pm

      I’m having the same issue. Did you solved?

      Reply
  71. Alex says

    June 1, 2017 at 10:20 am

    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

    Reply
  72. Ronald says

    June 15, 2017 at 5:23 am

    how do i insert the video directory path so i can access multiple videos on the html page?

    Reply
  73. atozexams says

    June 21, 2017 at 10:25 pm

    What is the difference between buffer and stream?

    Reply
  74. Linh Kute says

    July 1, 2017 at 11:10 am

    Hello, Sir ?

    Can you show me how to stream with cookie, thank you. I use to stream google drive

    Reply
  75. Lucifa says

    August 15, 2017 at 7:01 am

    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!

    Reply
  76. manoj says

    October 13, 2017 at 4:57 am

    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

    Reply
  77. Giuliano says

    November 16, 2017 at 11:32 am

    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.

    Reply
  78. neeraj says

    November 23, 2017 at 2:31 pm

    how we can set start time. Like need to set 10 sec. so video will direct start from 10 sec completion of video

    Reply
  79. Saurabh says

    January 3, 2018 at 5:23 am

    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?

    Reply
  80. Mik says

    January 3, 2018 at 2:27 pm

    Can i feed in videos directly from IP camera?

    Reply
  81. Vikash Kumar says

    February 14, 2018 at 2:24 am

    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?

    Reply
  82. Vipul Patel says

    April 17, 2018 at 9:18 am

    Hello Sir,

    I am unable to streaming with s3 bucket.
    I config all thing as per your guidance.

    Please help me.

    Reply
  83. swapnil says

    May 18, 2018 at 2:46 am

    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

    Reply
  84. Swapnil Shete says

    May 30, 2018 at 2:58 am

    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

    Reply
  85. Meer says

    June 27, 2018 at 5:04 am

    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

    Reply
  86. Durga Pratap says

    August 29, 2018 at 8:09 am

    include “./libraries/VideoStream.php”;
    $stream = new VideoStream(“my folder path”);

    ‘
    $stream->start();exit;

    But sir how to implement in video frame.

    Reply
  87. Durga Pratap says

    August 29, 2018 at 8:12 am

    And how to implement in website.

    Reply
  88. Yanming Wei says

    December 21, 2018 at 1:59 pm

    $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

    Reply
  89. sejpalsinh jadeja says

    March 26, 2019 at 10:18 pm

    Can please any one explain me where all code i have to put ??

    Reply
  90. Soma Satyanarayana says

    March 27, 2019 at 12:03 am

    how to eliminate download option

    Reply
  91. Chris says

    October 14, 2019 at 3:04 am

    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

    Reply
  92. Rick says

    April 23, 2020 at 3:16 pm

    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);

    Reply
    • Louis Mefor says

      May 20, 2020 at 6:56 pm

      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?

      Reply
    • Nick says

      May 22, 2020 at 3:29 am

      Type-error in $this->mimeType = $MINETYPES[$this->ext]; MIME instead of MINE .

      Reply
  93. Daniel says

    June 3, 2020 at 3:27 pm

    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?

    Reply
  94. Rana Ghosh says

    July 2, 2020 at 10:51 am

    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.

    Reply
  95. manishpanchal says

    July 21, 2020 at 1:29 am

    its not supprted on safari browser.
    Can u help me how to stream video on safari browser ?

    Reply
  96. intolap says

    August 24, 2020 at 12:05 pm

    $buffer variable is never used in the script.

    So, how does it affect the streaming?
    Also $buffer = 102400, what is this bytes or kbytes?

    Reply
  97. TAKONDWA says

    February 7, 2021 at 10:51 pm

    Am falling to connect to with html, help me with HTML code

    Reply
  98. iswaps says

    February 14, 2021 at 2:12 am

    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.

    Reply
  99. S. Chalisque says

    April 29, 2021 at 11:29 pm

    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.

    Reply
  100. Daruma says

    November 15, 2021 at 4:50 am

    Hello. Greet class. But how protect file? (hotlink)

    Reply
  101. zasrin says

    November 15, 2021 at 4:53 am

    Hey! Greet Class! Please help. How to protect video file? (hotlink).
    i use ngnix. valid_referers not working. 🙁

    Reply
  102. Dereck says

    February 6, 2022 at 4:52 pm

    Thank you, I like using php. It’s hard to find up-to-date resources, but this still works!!

    Reply
  103. Denis says

    February 27, 2022 at 3:56 am

    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.

    Reply
  104. Abdullah Nurum says

    June 7, 2022 at 12:48 pm

    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.

    Reply
  105. Micilini says

    November 16, 2022 at 4:37 pm

    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

    Reply

Trackbacks

  1. [SOLVED] How to create a video stream from a single dynamic image in PHP – BugsFixing says:
    May 10, 2022 at 1:15 am

    […] found this example for how to use PHP to streaming. It looks promisssing. But again the code supposes I have a video […]

    Reply
  2. [FIXED] XMLHTTPrequest plain text to blob (video) - FixeMe says:
    June 11, 2022 at 4:44 am

    […] NB : This JavaScript is fetching for this php code : https://codesamplez.com/programming/php-html5-video-streaming-tutorial But echo data has been changed by echo […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
    Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API
    "Facebooksdk" - C#.NET Library For Facebook API

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Using Supervisord Web Interface And Plugin
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
  • Beginning With Facebook Graph API C#.NET
  • LinQ Query With Like Operator
  • "Facebooksdk" - C#.NET Library For Facebook API

Recent Tutorials

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023