Reading mp4 files with PHP

You need to implement the skipping functionality yourself in PHP. This is a code snippet that will do that.


$path = 'file.mp4';


[email protected]($path,'rb');
if(!$fm) {
  // You can also redirect here
  header ("HTTP/1.0 404 Not Found");


if(isset($_SERVER['HTTP_RANGE'])) {
  if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
    if(!empty($matches[1])) {

  header('HTTP/1.0 206 Partial Content');
  header('HTTP/1.0 200 OK');

header("Content-Type: video/mp4");
header('Accept-Ranges: bytes');
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');


{ print fread($fm,min(1024*16,$end-$cur));

More Performance

Note that this is not the most efficient way to do it, because the whole file needs to go through PHP, so you will just need to try how it goes for you.

Assuming the reason you want to do this is to restrict access, and you need more efficiency later, you can use a flag for the web server.

Apache with X-Sendfile module or lightty (nginx info here)

$path = 'file.mp4';
header("X-Sendfile: $path");

This is a bit more advanced and you should only use it if you need it, but it is relaxing to know you have an upgrade option when you start out with something that is rather easy but has mediocre performance.

I found a much cheaper PHP-only way by experimenting with the accepted solution. Although I haven't tested this against X-Sendfile, I suspect the performance is even better overall for your site, since it means a shorter Apache file.

You only need the following code to be put out seekable .mp4 videos from PHP (haven't tested with .webm or other types):


header('Content-Type: video/mp4'); #Optional if you'll only load it from other pages
header('Accept-Ranges: bytes');


Much cleaner and faster; the accepted answer's code resulted in the video taking a very long time to load for some reason, loading the video with this code was instantaneous (both tests were on a local server with a 7.25 MB video file).

Tested with Chrome, Firefox, and Edge's default video players.

Edit: tested without header('Content-Type: video/mp4');, it still works if the file's loaded from another page! If you directly access the URL, there will be no video player; the code will just be printed out.