PHP 使用 X-Sendfile 的文件服务

PHP File Serving using X-Sendfile

我正在使用文件服务脚本构建网站。 此 脚本 允许网站传送 pdf、mp3 和 mp4 文件。 但只有 PDF 和 MP3 文件可用。 通过单击播放视频,我希望视频文件可以播放,但事实并非如此。视频控件已被禁用,无法播放。

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>

或者,到地址栏

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

其他人能找出我做错了什么吗?提前致谢。

我终于通过使用X-Sendfile apache模块

解决了这个问题
<?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.');
}