Search code examples
phphtmlfilemime

PHP File Serving using X-Sendfile


I'm building a website with a file serving script. This script allows the website to deliver pdf, mp3 and mp4 files. But only PDF and MP3 files were working. By clicking on the play video, I'im expecting the video file to play but it's not. The video controls have been disabled and unable to play.

files.php

<?php
error_reporting(E_All);

$fid = $_GET['fid'];
$ftype = $_GET['ftype']; // e.g. audios, videos, ebooks
$fcat = isset($_GET['cat']) ? $_GET['cat'] . '/' : ''; // e.g. lessons, more
$fext = '';
$fmime = '';

switch ($ftype) {
    case 'ebooks':
        $fext = '.pdf';
        $fmime = 'application/pdf';
        break;
    case 'audios':
        $fext = '.mp3';
        $fmime = 'audio/mp3';
        break;
    default:
        $fext = '.mp4';
        $fmime = 'video/mp4';
        break;
}

// example: audios/lessons/audio1.mp3
$file = $ftype . '/' . $fcat . str_replace('s', '', $ftype) . $fid . $fext;

if (file_exists($file))
{   
    // open the file as binary mode
    $fp = fopen($file, 'rb');

    // send the right headers
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Cache-Control: post-check=0, pre-check=0', false);
    header('Pragma: no-cache');
    header('Content-type: ' . $fmime);
    header('Content-Length: ' . filesize($file));

    // dump the file then stop the program
    fpassthru($fp);
    exit;
}
else
{
    die('File loading failed.');
}

video.php

<video src="/products/files.php?fid=1&ftype=videos&cat=lessons" autoplay controls></video>

alternatively, to the address bar

mydomain.com/products/files.php?fid=1&ftype=videos&cat=lessons

Could anyone else find out what I did wrong? Thanks in advance.


Solution

  • I finally solved this problem with the use of X-Sendfile apache module

    <?php
    if (file_exists($file))
    {
        // send the right headers
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header('Content-type: ' . $fmime);
        header('Content-Length: ' . filesize($file));
    
        // Make sure you have X-Sendfile module installed on your server
        // To download this module, go to https://www.apachelounge.com/download/
        header('X-Sendfile: ' . $file);
        exit;
    }
    else
    {
        die('File loading failed.');
    }