
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 bytesRange: bytes=1024-2047
requests the next chunkRange: 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:
- File Permissions: Ensure your web server can read video files
- Security Headers: Implement CORS if needed
- Error Logging: Set up comprehensive error tracking
- Load Testing: Test with concurrent users
- 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!
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
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..
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)
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
thank you 😀
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?
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)
This tutorial is great !!..
I have a question. Does the this streaming takes up bandwidth of the local server or s3 itself ?
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.
I thought so. Thanks for the reply.
Hi! Thanks a lot for the tutorial.
Do you know how to make it loop?
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!
@vasilis, no. You have to give the php script’s url in the src attribute of a HTML5 tag.
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
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.
Its not working
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 !
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
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.
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
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!
I to have the same doubt as krishna said…. plz will to explain with more clarity thanks!
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.
i’am trying to build a webapp to stream videos from client to rtmp server without uploading the file. is it possible ??
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
very very thank you, my life saver
Good one. Had issue playing mp4 video but now is playing.
How can I use for uploading video files to my server. I want it to upload files in chunks. Any suggestion will be appreciated.
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 ?
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).
thank you
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.
“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, …
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.
Hello I want the video to play on a div and not take the whole page , how can I?
thanks for that, saved me the hassle of writing it myself 😀
cheers
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
This is a very Informative and useful article. Thanks for sharing.
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.
Thanks for sharing. But I don’t really get why I should use this script and not simply embedd it with the HTML5 tag?
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.
Great! 100% working code, I only had to pass the correct path to my video ))) What a luck, thank you!
Great work!
But i doesn’t run for files larger than 2GB.
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
i need create a looping files….how to with this? thanks for helping!
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 .
helloo,,
how to combine source code HTML5 video streaming with API REST Web services.
Thanks for you helping,…!
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
Hello,
How do I add subtitles to the movie?
thanks
can u help me to be online my video streaming
Thanks
It helped a lot
wasted lots of time to get partial content working!
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
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?
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.
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
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]
You saved me a couple of hours! Thank you for posting this!
@HazCod: thanks for the modified version! Solved my “navigating away issue”.
Thanks. Really worked for me.
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!!
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!
Thanks! But not working on Safari! How to Fix This!
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 ?
hi, did you fix for safari?
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!
(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.
Hi Rana,
I need your help, how to find given url link is a video link in php.
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
hi, how can i save the session buffer and when the user refresh the page, the video starts at the last moment saved
Hello, im just wondering is it possible if the video dimension to be changed for example to be 800X600?
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.
thanks Rana, good stuff.
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?
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
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
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.
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. 🙂
Thanks nick…!
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 '’;
?>
Sorry, cannot post code here.
In Step 1, use the video element and type src= movie_Rana.php with apostrophs
Awesome man! Thanks a lot. It works like a dream.
Hii, I am new for CodeIgniter then i want to know that how to use this files in CodeIgniter.
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
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 ?
Thanks!
Works like a charm.
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();
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
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 ?
thanks your information
Thank you very much!!!
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
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
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}”?
Hi i thank you for giving streaming fuctionality. Is there any way to delete original file from path after streaming
hello
Great article, I’m trying to stream to player, I don’t want video autoplay. please help me thank.
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?
I’m having the same issue. Did you solved?
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
how do i insert the video directory path so i can access multiple videos on the html page?
What is the difference between buffer and stream?
Hello, Sir ?
Can you show me how to stream with cookie, thank you. I use to stream google drive
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!
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
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.
how we can set start time. Like need to set 10 sec. so video will direct start from 10 sec completion of video
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?
Can i feed in videos directly from IP camera?
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?
Hello Sir,
I am unable to streaming with s3 bucket.
I config all thing as per your guidance.
Please help me.
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
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
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]
include “./libraries/VideoStream.php”;
$stream = new VideoStream(“my folder path”);
‘
$stream->start();exit;
But sir how to implement in video frame.
And how to implement in website.
$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
Can please any one explain me where all code i have to put ??
how to eliminate download option
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
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);
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?
Type-error in $this->mimeType = $MINETYPES[$this->ext]; MIME instead of MINE .
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?
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.
its not supprted on safari browser.
Can u help me how to stream video on safari browser ?
$buffer variable is never used in the script.
So, how does it affect the streaming?
Also $buffer = 102400, what is this bytes or kbytes?
Am falling to connect to with html, help me with HTML code
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.
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.
Hello. Greet class. But how protect file? (hotlink)
Hey! Greet Class! Please help. How to protect video file? (hotlink).
i use ngnix. valid_referers not working. 🙁
Thank you, I like using php. It’s hard to find up-to-date resources, but this still works!!
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.
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.
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
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