提问人:user1427930 提问时间:10/2/2023 更新时间:10/2/2023 访问量:25
在 php 中显示文件而不阻止应用程序
Display files without block the app in php
问:
我在 Apache2 上提供了一个 php 应用程序。在一个函数中,我只想显示媒体,使用 php 脚本而不是将媒体托管在服务器上的公共文件夹中。
这是因为我希望能够添加功能来控制登录用户以后的权限,并首先检查文件扩展名等。
我尝试了 fpassthru 和 readfile,这两个功能都完全阻止了应用程序。尤其是当有 10mb >的视频时。
下面是代码的一个版本:
display_file.php?filename=foo.jpg
if (empty($_GET['filename']))
{
die(http_response_code(500)):
}
$filename = $_GET['filename'];
$extension = file_extension($filename); // .jpg|.mp4 etc
$mime = mime($ext); // get mine_type
$uri = '/foo/bar/'.$filename;
// Only allow sertain extensions
if (!in_array($ext, ALLOWED_FILE_EXTENSIONS)) // ['jpg','png','mp4'...]
{
die(http_response_code(403));
}
// File doesn't exist
if (!file_exists($uri))
{
die(http_response_code(404));
}
$size = filesize($uri);
$start = 0;
$end = $size - 1;
$time = filemtime($uri);
$expires = gmdate('D, d M Y H:i:s \G\M\T', $time + (60 * 60));
$modified = gmdate('D, d M Y H:i:s \G\M\T', $time);
//$fp = fopen($uri, 'rb');
header('Pragma: cache');
header('Cache-Control: max-age=31536000');
header('Expires: '.$expires);
header('Content-Type: '.$mime);
header('Content-Length: '.$size);
header('Accept-Ranges: bytes');
header("Content-Range: bytes $start-$end/$size");
header('Last-Modified: '.$modified);
//fpassthru($fp);
readfile($uri);
如果我使用 Apache2 直接通过公用文件夹显示文件,则该应用程序不会被阻止。
有没有其他方法可以在不阻止整个应用程序的情况下提供/显示带有 php 用户检查、扩展名等的文件?
答:
0赞
symcbean
10/2/2023
#1
您的分析/描述不清楚。“阻止应用程序”是什么意思?你是怎么衡量的?
我怀疑这里发生的事情是会话被阻止,而不是应用程序,尽管内容文件可能存在锁定问题。
您向我们展示的代码不会阻止会话 - 没有会话。但代码显然是不完整的。添加 before 将解决(或使用非阻塞会话处理程序)。session_write_close()
readfile()
锁定内容文件的可能性较小 - 但您没有告诉我们这是在哪个操作系统上运行的,因此我们无法告诉您如何进一步调查。
评论