Reputation: 291
I am trying to stream videos to only authenticated users using php.
Below is the code I am trying, but unable to play mp4 video.
index.php
<video controls="" autoplay="" name="media">
<source src="http://localhost/video_test/mp4.php" type="video/mp4">
</video>
mp4.php
$newfile = '/var/www/html/video_test/videos/MyVideo.mp4';
if (file_exists($newfile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($newfile));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($newfile));
ob_clean();
flush();
readfile($newfile);
exit;
}
?>
Upvotes: 2
Views: 2698
Reputation: 192
I'm already working on a similar project so I've grabbed some of the code and stripped-out everything bar the essentials :-
The videos are named 000000.mp4 ~ 999999.mp4 and for the time being, put into the same directory as the PHP code (We will move them later).
This is the page that plays the video :-
<HTML>
<BODY>
<CENTER>
<?php // video-play.php
$vid = (int) $_GET['vid']; // Get video ID
echo "<VIDEO HEIGHT='95%' SRC='video-file.php?vid=$vid' CONTROLS='true' AUTOPLAY='true'>\n</VIDEO>\n";
?>
</CENTER>
</BODY>
</HTML>
You play video 000001.mp4 with video-play.php?vid=1
This is the bit that gets the video file and sends it to the browser :-
<?php // video-file.php
$vid = (int) $_GET['vid']; // Get video ID
$vfn = sprintf("%06d.mp4",$vid); // Get video file from ID
$ok = true;
// Code to check if user can view video goes here
if ($ok)
{
header("Content-Type: video/mp4");
header('Pragma: public');
header('Content-Length: '.filesize($vfn));
readfile($vfn);
}
else
{
echo "<HTML>\n<BODY>\n";
echo "<CENTER>\n";
echo "<H2> Access Denied ! </H2>";
echo "</CENTER>\n";
echo "</BODY>\n</HTML>\n";
}
?>
When you have got this working you can move the videos to a directory that can't be read from the Internet (eg /var/www/videos ) and change line 3 in video-file.php to read :-
$vfn = sprintf("../videos/%06d.mp4",$vid); // Get video file from ID
The reason we use video-file.php is because other wise the video could be played by simply entering http://your-domain.com/000001.mp4 into your browser - bypassing any controls.
When you have got that working, you need to decide how to control access. The easiest way is probably via sessions.
Hope this helps
Upvotes: 3