Skip to content
Advertisement

How to serve a video from a file outside the web root in PHP to a html5 video source

I currently have a file called index.php in my web root folder/var/www/html/ which should load an image and a video in a directory outside of the web root.

The image and a video file is located outside the web root folder as follows: /var/www/media/image.jpg and /var/www/media/movie.mp4.

To access the image file, I have created a php file within the web root folder calledserve_image.php with the following contents:

<?php
  header('Content-Type: image/jpg');
  readfile("../media/image.jpg");
?>

then, within index.php, i load this image into an <img> element as follows:

<html>
  <body>
    <img width="320" height="240" src="serve_image.php"/>
  </body>
</html>

and the image is correctly displayed.

If I try to do the same thing with the mp4 file, it does not show the video. I have created a php file within the web root folder serve_movie.php with the following contents:

<?php
  header('Content-Type: video/mp4');
  readfile("../media/movie.mp4");
?>

then, within index.php, i load try to load this movie into an <source> element within a <video> element as follows:

<html>
  <body>
    <video width="320" height="240" controls autoplay>
      <source src="serve_movie.php" type="video/mp4"/>
    </video>
  </body>
</html>

However, no video is shown.

What do I need to do to correctly load the video?

Advertisement

Answer

Your code looks correct, and when I’ve just tested a very similar script, it has worked perfectly.

A couple of thoughts:

  • Have you tried accessing your video script (serve_movie.php) directly within your browser to see if you get the video?
  • Do you have error reporting turned on, and set to display errors? If so, are you getting any? I’m wondering if reading in the content of your video is exhausting PHP’s memory limit due to its size.

To enable error reporting, add the following to your video script (serve_movie.php) before any other code:

error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', true);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement