【问题标题】:Send file using php without exposing directory使用php发送文件而不暴露目录
【发布时间】:2019-09-18 06:19:28
【问题描述】:

这些是我的设置:

Web Server: Apache/2.4.25
Web structure:
 /
 |__Video/
         |__ test.mp4
 |__play.php

目前我正在公开我的服务器上的所有视频,直接将视频目录放在 apache 目录中。

我想要获得的是将视频移到 Apache 目录之外(假设没有权限问题)并通过 GET 请求仅将请求的视频传输到play.php,例如:GET play.php?req=test.mp4

目前我已经编写了以下代码:

$name = $_GET['req']
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($name));
header('Content-Type: ' . mime_content_type($name));
header('Content-Disposition: filename="'.$name.'"');
readfile($name);
exit;

缺少什么?当我尝试使用 play.php 访问文件时,为什么会得到“不支持的视频媒体”?使用“mysite.com/Video/test.mp4”,我可以毫无问题地直接访问媒体。

我意识到,如果我等待足够长的时间,浏览器会完全下载文件并重现它。我无法获得的是文件的流式传输。

【问题讨论】:

  • 调用mime_content_type的值是多少?我怀疑这不是你想的那样。您是否尝试过手动指定正确的 mime 类型?
  • @Dave mime_content_type 提取正确的信息,我使用 cUrl 检查。顺便说一句,确保我使用了以下内容:'Content-Type: video/mp4' 没有任何更改。我意识到,如果我等待足够长的时间,两种方式都会让浏览器完全下载文件并重现它。

标签: php apache file http-headers


【解决方案1】:

我找到了问题和可能的解决方案。

  1. 问题出在文件读取中,它在浏览器处理之前传输了整个文件。
  2. 一种可能的解决方法是使用X-SendFile 模块。

如果你像我一样使用 Debian 就足够了:

  • 安装它:sudo apt-get install libapache2-mod-xsendfile
  • 修改您的站点配置(默认路径:/ect/apache2/sites-available)在开头(或选择的虚拟主机)添加以下行:
XSendFile on
XSendFilePath /full/path/to/directory1
XSendFilePath /full/path/to/directory2
  • 重启网络服务器:sudo systemctl reload apache2 && sudo systemctl restart apache2
  • 这样更新php脚本:
$name = "/full/path/to/directory1/".$_GET['req']
header('Accept-Ranges: bytes');
header('Content-Length: ' . filesize($name));
header('Content-Type: ' . mime_content_type($name));
header('Content-Disposition: filename="'.$name.'"');
header('X-Sendfile: $name');

建议您访问this page了解更多信息。

【讨论】:

    猜你喜欢
    • 2021-03-13
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多