https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_b964594d3d957944241961017b9eb19bf02834de44cce93d8e67dd306852dbe346167181e455e33d5268ea01d973d77bb056848546f31794f31a4c31a9da5aa3.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_23f1ae74c634d7e5e0a067c22b7a8c2d79c3ffd9a3b9395fc82c1b3b99635552b994f1f72f532f28ceaff1ea054ea026cd488cd62fa03a4ad91d212b5f3c5a72.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_451c3884f51125f7687e5bb07cfab033c04cb7174c33f93213b2af4bad2af13cf48b92a7fa95fc86d7d436f355938a3ac50aa119cdb7c9b6d5a52815c3e6033e.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_bfff9e63e857e9ee612e292d4a6edf3ced64d6a756925c953a9d8f77845ff601eca64d73dfa48756b1a9f4a4d6de6127a273bcde16ddeb71a22383460f4e94b0.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_f4dd7e1d73ae5eda35ed5ad6aa965b612dbf483ece3ca50c1e8e30ad8dff1c66a160ed75e958e2db399661d229874783e0834ad813a479437035666b8e9e3386.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_4fce0769137d4cd096989b0349bc3c2bbfca79ac311fdf714c41ab24d87551c7b49b756c8a8de090b0714a0ad0560e49fa532ba5a88875ea4afd78efac464df6.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_85cec8b07d60426b11040e471babca0d2f9c8dc87a9b56e06cad39828f7f67179e29609100f282a574872c9a93fb635b25416300eb4c97bc5a653d00cf6f8dbf.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_6768e5a27d4d357347338621c0d20bd269b126d30eec796193390f2f530fbaea60af84130c46f9786114be65149e661e87d55c339219c90aa76396d7e5b734ef.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_2acd6bdff3b680341e8c727da5169a647123eb8fd0a90253161b4c3af272c15d293bf9bb217008bb13f84d1910b0e166798001f8603b6c026d5c20a76c41d47c.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_a3e961b1c02e0b9934a8632afee4aa4b6cf5327df8db18c33549f988eace16ac9539b648e66c07f23442868afe19cc90a3f7aa1671da4d2a8ef511860022df54.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_268c9bba6ba649318f0da28c37b09a9bbfa371210f9b6b52faa7fd8ae94abf6b3c3bfeb5df5705c93495ce1152ca58aeabc435d6c6c1bd959025165c3f50e086.js
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • Advanced Python Topics
    • AWS Learning Roadmap
    • JWT Complete Guide
    • Git CheatSheet
  • Explore
    • Programming
    • Development
      • microservices
      • Front End
    • Database
    • DevOps
    • Productivity
    • Tutorial Series
      • C# LinQ Tutorials
      • PHP Tutorials
  • Dev Tools
    • JSON Formatter
    • Diff Checker
    • JWT Decoder
    • JWT Generator
    • Base64 Converter
    • Data Format Converter
    • QR Code Generator
    • Javascript Minifier
    • CSS Minifier
    • Text Analyzer
  • About
  • Contact
CodeSamplez.com

CodeSamplez.com

Programming And Development Resources

You are here: Home / Programming / PHP Video Streaming: Building Your Own Video Streaming Server

PHP Video Streaming: Building Your Own Video Streaming Server

Updated May 23, 2025 by Rana Ahsan 133 Comments ⏰ 8 minutes

PHP Video Streaming Guide

Building a video streaming platform doesn’t require expensive third-party services or complex infrastructure. With PHP, you can create your own robust video streaming solution that handles everything from basic playback to advanced seeking functionality. I worked with PHP video streaming in one of my work project, and I’m excited to share the exact techniques that transformed my simple video server into a professional-grade streaming platform.

Why PHP Video Streaming Matters

Video content dominates the internet. Users expect seamless playback, instant seeking, and fast loading times. Traditional video serving methods simply dump the entire file to the browser, which creates terrible user experiences and wastes bandwidth.

PHP video streaming solves these problems by implementing byte range requests and progressive loading. This means your users get instant playback, perfect seeking functionality, and your server saves massive amounts of bandwidth.

Understanding Byte Range Requests

Before diving into the code, you need to understand how modern video streaming actually works. When a user clicks play or seeks to a specific timestamp, their browser sends a Range header to your server. This header tells your PHP script exactly which bytes of the video file to send back.

For example:

  • Range: bytes=0-1023 requests the first 1024 bytes
  • Range: bytes=1024-2047 requests the next chunk
  • Range: bytes=500000- requests everything from byte 500,000 onwards

This is revolutionary because it enables true streaming functionality. Users can jump to any part of your video instantly without downloading the entire file first.

The Complete PHP Video Streaming Class

Here’s the updated and improved VideoStream class that handles all modern streaming requirements:

<?php
class VideoStream
{
    private $path = "";
    private $stream = null;
    private $buffer = 262144; // 256KB buffer for optimal performance
    private $start = -1;
    private $end = -1;
    private $size = 0;
    
    function __construct($filePath) 
    {
        $this->path = $filePath;
    }
    
    /**
     * Initialize and validate the video file
     */
    private function init()
    {
        // Validate file exists and is readable
        if (!file_exists($this->path) || !is_readable($this->path)) {
            header("HTTP/1.1 404 Not Found");
            exit;
        }
        
        $this->size = sprintf("%u", filesize($this->path));
        $this->start = 0;
        $this->end = $this->size - 1;
    }
    
    /**
     * Parse Range header and set start/end positions
     */
    private function parseRange()
    {
        if (!isset($_SERVER['HTTP_RANGE']) || 
            !preg_match('/bytes=(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $matches)) {
            return;
        }
        
        $start = $matches[1];
        $end = $matches[2];
        
        if (!empty($start)) {
            $this->start = intval($start);
        }
        
        if (!empty($end)) {
            $this->end = min(intval($end), $this->size - 1);
        }
    }
    
    /**
     * Set appropriate headers for video streaming
     */
    private function setHeaders()
    {
        // Prevent caching issues
        header("Cache-Control: no-cache, no-store, must-revalidate");
        header("Pragma: no-cache");
        header("Expires: 0");
        
        // Set content type based on file extension
        $mimeType = $this->getMimeType();
        header("Content-Type: {$mimeType}");
        
        // Set range headers
        header("Accept-Ranges: bytes");
        header("Content-Length: " . ($this->end - $this->start + 1));
        
        if ($this->start > 0 || $this->end < ($this->size - 1)) {
            header('HTTP/1.1 206 Partial Content');
            header("Content-Range: bytes {$this->start}-{$this->end}/{$this->size}");
        }
    }
    
    /**
     * Get MIME type for video file
     */
    private function getMimeType()
    {
        $extension = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
        
        $mimeTypes = [
            'mp4' => 'video/mp4',
            'webm' => 'video/webm',
            'ogg' => 'video/ogg',
            'avi' => 'video/x-msvideo',
            'mov' => 'video/quicktime',
            'wmv' => 'video/x-ms-wmv',
            'flv' => 'video/x-flv'
        ];
        
        return isset($mimeTypes[$extension]) ? $mimeTypes[$extension] : 'application/octet-stream';
    }
    
    /**
     * Stream the video content to browser
     */
    public function start()
    {
        $this->init();
        $this->parseRange();
        $this->setHeaders();
        
        // Create stream context for better performance
        $context = stream_context_create([
            'http' => [
                'method' => 'GET',
                'timeout' => 30
            ]
        ]);
        
        if (!($this->stream = fopen($this->path, 'rb', false, $context))) {
            header("HTTP/1.1 500 Internal Server Error");
            exit;
        }
        
        // Seek to start position
        if ($this->start > 0) {
            fseek($this->stream, $this->start);
        }
        
        // Stream the content in chunks
        $this->readBuffer();
        fclose($this->stream);
    }
    
    /**
     * Read and output file buffer
     */
    private function readBuffer()
    {
        $bytesToRead = $this->end - $this->start + 1;
        
        while (!feof($this->stream) && $bytesToRead > 0) {
            $chunkSize = min($this->buffer, $bytesToRead);
            $chunk = fread($this->stream, $chunkSize);
            
            if ($chunk === false) {
                break;
            }
            
            echo $chunk;
            flush();
            
            $bytesToRead -= strlen($chunk);
            
            // Prevent timeout on slow connections
            if (connection_status() !== CONNECTION_NORMAL) {
                break;
            }
        }
    }
}
?>
Code language: HTML, XML (xml)

Setting Up Your Video Streaming Endpoint

Creating your streaming endpoint is surprisingly straightforward. Here’s how you implement it:

<?php
// stream.php - Your video streaming endpoint
require_once 'VideoStream.php';

// Validate video parameter
$videoFile = isset($_GET['video']) ? $_GET['video'] : null;

if (empty($videoFile)) {
    header("HTTP/1.1 400 Bad Request");
    echo "Video parameter is required";
    exit;
}

// Sanitize file path to prevent directory traversal attacks
$videoFile = basename($videoFile);
$videoPath = "videos/" . $videoFile;

// Additional security: check file extension
$allowedExtensions = ['mp4', 'webm', 'ogg', 'mov', 'avi'];
$fileExtension = strtolower(pathinfo($videoFile, PATHINFO_EXTENSION));

if (!in_array($fileExtension, $allowedExtensions)) {
    header("HTTP/1.1 403 Forbidden");
    echo "File type not allowed";
    exit;
}

// Initialize and start streaming
$stream = new VideoStream($videoPath);
$stream->start();
?>
Code language: HTML, XML (xml)

HTML5 Video Integration

The magic happens when you combine your PHP streaming backend with HTML5 video elements. Here’s the complete frontend implementation:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Video Streaming Player</title>
    <style>
        .video-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        
        video {
            width: 100%;
            height: auto;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .video-controls {
            margin-top: 15px;
            text-align: center;
        }
        
        .video-list {
            margin-bottom: 20px;
        }
        
        .video-btn {
            margin: 5px;
            padding: 10px 15px;
            background: #007cba;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .video-btn:hover {
            background: #005a8c;
        }
    </style>
</head>
<body>
    <div class="video-container">
        <h1>Professional Video Streaming Platform</h1>
        
        <div class="video-list">
            <button class="video-btn" onclick="loadVideo('sample-video.mp4')">Sample Video 1</button>
            <button class="video-btn" onclick="loadVideo('demo-content.webm')">Demo Content</button>
            <button class="video-btn" onclick="loadVideo('tutorial.mov')">Tutorial Video</button>
        </div>
        
        <video id="videoPlayer" controls preload="metadata">
            <source src="" type="">
            Your browser doesn't support HTML5 video streaming.
        </video>
        
        <div class="video-controls">
            <p>Click any video above to start streaming instantly!</p>
        </div>
    </div>
    
    <script>
        function loadVideo(filename) {
            const video = document.getElementById('videoPlayer');
            const source = video.getElementsByTagName('source')[0];
            
            // Update source with streaming endpoint
            source.src = `stream.php?video=${encodeURIComponent(filename)}`;
            source.type = getVideoMimeType(filename);
            
            // Reload video element
            video.load();
            
            // Auto-play after loading
            video.addEventListener('loadeddata', function() {
                video.play().catch(e => {
                    console.log('Autoplay prevented by browser policy');
                });
            }, { once: true });
        }
        
        function getVideoMimeType(filename) {
            const extension = filename.split('.').pop().toLowerCase();
            const mimeTypes = {
                'mp4': 'video/mp4',
                'webm': 'video/webm',  
                'ogg': 'video/ogg',
                'mov': 'video/quicktime',
                'avi': 'video/x-msvideo'
            };
            return mimeTypes[extension] || 'video/mp4';
        }
        
        // Enhanced video player with streaming analytics
        document.getElementById('videoPlayer').addEventListener('progress', function() {
            const buffered = this.buffered;
            if (buffered.length > 0) {
                const bufferedEnd = buffered.end(buffered.length - 1);
                const duration = this.duration;
                const bufferedPercent = (bufferedEnd / duration) * 100;
                console.log(`Buffered: ${bufferedPercent.toFixed(1)}%`);
            }
        });
    </script>
</body>
</html>
Code language: HTML, XML (xml)

Advanced Security and Optimization

Security becomes critical when you’re serving video content. Here’s how to protect your streaming server:

1. Authentication Layer

<?php
// Add authentication to your streaming endpoint
session_start();

function validateUser() {
    if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
        header("HTTP/1.1 401 Unauthorized");
        exit("Authentication required");
    }
}

function checkVideoAccess($userId, $videoFile) {
    // Implement your access control logic here
    // Check database permissions, subscription status, etc.
    return true; // Return false to deny access
}
?>
Code language: HTML, XML (xml)

2. Rate Limiting

<?php
class RateLimiter {
    private $maxRequests = 50; // Requests per hour
    
    public function checkLimit($identifier) {
        $key = "rate_limit_" . md5($identifier);
        $requests = apcu_fetch($key, $success);
        
        if (!$success) {
            $requests = 0;
        }
        
        if ($requests >= $this->maxRequests) {
            header("HTTP/1.1 429 Too Many Requests");
            exit("Rate limit exceeded");
        }
        
        apcu_store($key, $requests + 1, 3600);
    }
}
?>
Code language: HTML, XML (xml)

3. CDN Integration

For production environments, you’ll want to integrate with Content Delivery Networks:

<?php
function getCDNUrl($videoFile) {
    $cdnDomain = "https://your-cdn.example.com";
    $hashedPath = md5($videoFile . time());
    return "{$cdnDomain}/stream/{$hashedPath}/{$videoFile}";
}
?>
Code language: HTML, XML (xml)

Performance Optimization Strategies

The difference between a good streaming server and a great one lies in optimization. Here’s what actually matters:

Buffer Size Tuning

Different video types require different buffer sizes. Large buffers work better for high-quality videos but consume more memory. Start with 256KB and adjust based on your specific needs.

Memory Management

Always use fread() with proper chunk sizes instead of loading entire files into memory. This prevents memory exhaustion on large video files.

Connection Handling

Implement proper connection status checking to prevent wasted resources on closed connections.

Troubleshooting Common Issues

Safari Compatibility Problems

Safari on macOS can be particularly challenging with video streaming. The solution involves setting specific headers:

// Add these headers for Safari compatibility
header("Accept-Ranges: bytes");
header("Content-Transfer-Encoding: binary");
Code language: JavaScript (javascript)

Seeking Performance

If users experience slow seeking, check your buffer size and ensure you’re properly implementing byte range requests. The parseRange() method in our class handles this automatically.

Mobile Device Support

Mobile browsers require additional considerations:

// Mobile-specific optimizations
if (preg_match('/Mobile|Android|iPhone|iPad/', $_SERVER['HTTP_USER_AGENT'])) {
    $this->buffer = 65536; // Smaller buffer for mobile
}
Code language: PHP (php)

Production Deployment Checklist

Before launching your PHP video streaming platform, verify these critical elements:

  1. File Permissions: Ensure your web server can read video files
  2. Security Headers: Implement CORS if needed
  3. Error Logging: Set up comprehensive error tracking
  4. Load Testing: Test with concurrent users
  5. Backup Strategy: Plan for video file redundancy

Conclusion

PHP video streaming opens incredible possibilities for developers who want full control over their video delivery. The streaming class we’ve built handles byte range requests perfectly, provides excellent seeking performance, and scales beautifully with proper optimization.

Remember that successful video streaming depends on both server-side implementation and client-side experience. The combination of our PHP streaming backend with modern HTML5 video elements creates a professional-grade platform that rivals expensive third-party solutions.

Start implementing this streaming solution today, and you’ll quickly discover why so many developers choose PHP for video streaming projects. The flexibility, performance, and cost savings make it an absolutely compelling choice for any video-centric application.

Whether you’re building a learning management system, entertainment platform, or corporate video portal, this PHP video streaming foundation will serve you incredibly well. The code is production-ready, secure, and optimized for real-world usage.

Want to level up your PHP skill? Explore more PHP Tutorials!

Share if liked!

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

You may also like


Discover more from CodeSamplez.com

Subscribe to get the latest posts sent to your email.

First Published On: March 24, 2014 Filed Under: Programming Tagged With: html5, php

About Rana Ahsan

Rana Ahsan is a seasoned software engineer and technology leader specialized in distributed systems and software architecture. With a Master’s in Software Engineering from Concordia University, his experience spans leading scalable architecture at Coursera and TopHat, contributing to open-source projects. This blog, CodeSamplez.com, showcases his passion for sharing practical insights on programming and distributed systems concepts and help educate others.
Github | X | LinkedIn

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. 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: [email protected]

    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 : [email protected]

    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 [email protected] 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
  106. Ryahu Gmikyu says

    February 4, 2024 at 8:50 PM

    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

    Reply

Leave a ReplyCancel reply

Primary Sidebar

  • Facebook
  • X
  • Pinterest
  • Tumblr

Subscribe via Email

Top Picks

python local environment setup

Python Local Development Environment: Complete Setup Guide

In-Depth JWT Tutorial Guide For Beginners

JSON Web Tokens (JWT): A Complete In-Depth Beginners Tutorial

The Ultimate Git Commands CheatSheet

Git Commands Cheatsheet: The Ultimate Git Reference

web development architecture case studies

Web Development Architecture Case Studies: Lessons From Titans

static website deployment s3 cloudfront

Host Static Website With AWS S3 And CloudFront – Step By Step

Featured Dev Tools

  • Diff Checker
  • JWT Decoder

Recently Published

service worker framework integration

Service Workers in React: Framework Integration Guide

service worker caching strategies

Service Worker Caching Strategies: Performance & Offline Apps

service worker lifecycle

Service Worker Lifecycle: Complete Guide for FE Developers

what is service worker

What Is a Service Worker? A Beginner’s Guide

Dynamic Typing In Python

Dynamic Typing in Python: A Comprehensive Guide For Beginners

Footer

Subscribe via Email

Follow Us

  • Facebook
  • X
  • Pinterest
  • Tumblr

Explore By Topics

Python | AWS | PHP | C# | Javascript

Copyright © 2025

https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_e23e7f6287efaa39cb4ae7b32e09123bbf9ab01c2d30e4d8e2a7a68f1292dd2293acd43379ee1610563188438414b446176c052cc7ab050943fb33afd2559fc4.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_c402e38f1879c18090377fb6b73b15ac158be453ecda3a54456494fe8aba42b990c293bae5424e5643d52515ffc2067e0819995be8d07d5bba9107a96780775c.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_ffc3511227531cc335353c54c3cbbaa11d0b80e5cb117478e144436c13cd05495b67af2e8950480ed54dbdabcdcef497c90fdb9814e88fe5978e1d56ce09f2cf.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_d57da9abfef16337e5bc44c4fc6488de258896ce8a4d42e1b53467f701a60ad499eb48d8ae790779e6b4b29bd016713138cd7ba352bce5724e2d3fe05d638b27.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_edc0e9ef106cc9ef7edd8033c5c6fcff6dc09ee901fd07f4b90a16d9345b35a06534f639e018a64baaf9384eee1df305570c1ecad747f41b787b89f53839962b.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_bc2182bb3de51847c8685df18692deda654dbf90fb01b503eb1bb0b68b879a051b91f30a9210ed0b2ba47c730db14b159cd9391ffdcd7117de397edd18366360.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_dccc492dbbfdac33d1411f9df909e849c7268fcf99b43007f278cde3a0adc0ae00e8cae5ec81cf255b9a6eae74e239ba1fa935572af77173219cb081f7d2327d.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_00bacf9e36181aac2b666d110cd9d82257f846766e7041b2d7b3c909b458982931ccc9b203e37098fbdfcf43ca359cf04e3824a724a6789fc204196d3a72ad29.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_65d41e8acf8460659d5800381e03c2a9dd52ec71287a6f20307e1eb7da27691a8e74e4408e23656afa7b5bd74b82697984fd2b1d4501251c6e73c6a935b6b92f.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_aa5a5d229b421633f4247380e1e8c0a4854f82efb35d13a5b07b7b8fbe22e98842a580f063e5965345a51c477a7f5c2585edf8dd7d896b2438dc61f91d8d970c.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_bb8058a9e234a7ffaa98891b1df7f6b8e67410e6984568b151daa05113b8c7f89d7b5918ae73f020998a16f7f5a087a13d6a9a5e5d7c301e2ca12fd9d1f8d177.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_647fb67570c6108fb10ae6785a1abdbecac99ffcf80351d0bef17c3cf783dce497b1895fcdaae997dacc72c359fbfb128cc1540dd7df56deb4961e1cd4b22636.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_f7a298a0f1f754623fe3b30f6910ce2c1373f715450750bd7a391571812b00df1917e2be90df6c4efc54dbdfda8616278a574dea02ba2c7a31992768df8db334.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_df30604d5842ef29888c3c1881220dc6d3f8854666d94f0680c5f38aa643c5fb79b10eb9f10998d8856eb24ca265783195937434fd6c2bb8e4846df0277a7fb7.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_f17fe6fb0993f1703181d7ae9e9ea570f3d33a43afd6f2a4567daa1a6745698c7b8193dc72d50991d2dd87cd3dcf663959206607d193a9b57926d061a1f50aef.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_945dcbab2c2a131f3c90f4fb91776b76066d589f84fb55bff25cd5d79a56218000616bfca1f0af9a74f32348693707af49e8fe624de8aa34f1e1c5b6a25709cf.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_65820d252e1b93596de6697fd5f02483f3e2524a0696c7d698b64745edb32bf5831a90e556842f5f88c8209766cc78ca3a41cf783d20236a9f90d4a7ea7b3e72.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_7286884797a1210857e2a36f8ab46604b0034b6abf512380447a5763c873db6a72b8547f660053de0ea69faef1eb64878f39ff4b0ea86c963efab95764a3bf5b.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_cbcf6c279ac6c6a25ae138bf964e64a5fd90d22dcdf8a53b6fe7b72cefa51063bfb0181a6e50dd2acdcae2795619887d1d83b10461e44e5103be756f2588d837.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_47965bc586b95810c925b9df3314e0c9a5cd121e70ca0831f87df0bc034695de4f83ecf2def86f737e14614ee138794473cf32cd3082a5d38db9dec0c1f266fa.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_12aa201cea075846d266536aa222d64d4088b851d87f55dac5e611b77add6826c8ebc6e82650fcd1a9e88a05a0072dedd195719c5f64cd4580a0acd8aee05d92.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_eaa93529c38925eb07368c361382956fbd910b5106b8589fa7e2e15a59c46437de3698d50ec4754bc45e6dfac47b3f41cc4c6112d7ede071ca8950385d4987dc.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_7114b99ac68dccd26df4c64e5cdfccb7a7580b30a6160a9341f630f0e0fa3960fcae14b2d412d57b40a8000c9d8314a02fa986a5966dccfa75d755740e315822.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_d87ea86dd0e7ecdd5fe7a5bb67becf943e57c3add866b456034d51663d099031bd563e12f61fdccc044969adf938a8584ed22ccd401ab8b669e20e4f92fb54e8.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_35311c3d71a3605fad4e1d6b50f3911311cdcc46418bdf56d6d0308a75a69585269ee7582a335e29989adf308fa1a81a10a2c2d4e257e9d680447a4996f6269e.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_f4fc182ef03c12e9dcadd6febc3dbaa4a29134469057ca9e8ec0be2f2de29a494514ff4b59798e74debf26f78b2df2b3e2665c69b77035761fb463b783202915.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_85c0f2769456e60153b0fd8364b82a035da53384f62de342d9bdca806f3f1ea56486919a00497a18d457949c82bf8bfacc4423fc332074ddf71a49a8fe628fff.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_67f99bef3678c549a14b5f2ff790cce6aba338dca29020755444231b45fa0f980f795e3658496ba70739a099b47b22bc2eab564343ac6132309de3adbbae3455.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_09eecfdd96206ed13830b4b93cfb2cc75cd38083671a34194437b5734b5bb38712209dc335b07e3266ceb3c3a44a155b9bbe5f3e0e1105b19dd45d3def76f020.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_4c089fbdb88e3b624a6f884d3ba1bf606f003bfcd3742376d0d353cd62181dc663aa3811a56361c3100de488fc4d6595a50de2b26f058921ba74f5f2c1b5be00.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_897ff6ac314c5f5e0f496c6af624bd9abf296a02cb5aeb850b9220b6dc3ce2fc4004cb02ed8b59d59d4b9c9d90f050d6eebc1d08ecaebab2f671f7d9367e6410.js
https://codesamplez.com/wp-content/cache/breeze-minification/js/breeze_67d1e619e71d36ae00ddcf85ee18628bb4eb64fcb3d6119b463e75cb987013420a21136d19cd03e6634ccc01cfa9af4a357930e4cf6900953b7812efb4f249fb.js