如何使用PHP从Web根目录外部提供文档? [英] How to serve documents from outside the web root using PHP?

查看:176
本文介绍了如何使用PHP从Web根目录外部提供文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了安全起见,我将文件和文件夹的集合移到apache服务器上的Web根目录之外,然后我将为它们提供动态服务. 这似乎比2个替代方案要好:

For security I'm moving a collection of files and folders to outside the web root on an apache server, and then I will serve them dynamically. This seems better than 2 alternatives:

  1. 让他们可以访问网络,只需创建一个php登录页面,该页面将添加到每个文件的前面.问题是它们不是全部的php文件,我不能将php登录文件添加到pdf,图像等之前.
  2. 让他们可以访问网络,并使用HTTP身份验证来限制对整个目录的访问.但这会带来一些问题,包括明文密码,没有优雅的注销方法等.

因此,我们将其返回到Web根目录之外,但要动态地为其提供服务.我遇到的问题是,因为它们都是不同的文件类型(php脚本,txt,pdf,jpg),所以我不确定应该使用include()还是readfile().而且我在为每个文件发送正确的标题时遇到了问题,以便浏览器正确显示它们.

So we're back to having them outside the web root but serving them dynamically. The problem I'm having is, since they're all different file types (php scripts, txt, pdf, jpg) I'm not sure whether I should use include() or readfile(). And I run into problems with sending the proper headers for every file so that the browser displays them correctly.

我想念另一个魔术解决方案吗?是否有一个让我无法处理动态文件和标头服务的框架?

Am I missing another magic solution? Is there a framework that has eluded me that handles the serving of dynamic files and headers?

(仅供参考,我正在共享主机上运行Linux,Apache和PHP)

(FYI I'm running Linux, Apache & PHP on a shared host)

推荐答案

我认为这样会起作用:

<?php
$path = realpath(dirname(__FILE__) . '/../my_files/' . $_GET['file']);

$parts = explode('/', pathinfo($path, PATHINFO_DIRNAME));
if (end($parts) !== 'my_files') {
    // LFI attempt
    exit();
}

if (!is_file($path)) {
    // file does not exist
    exit();
}

header('Content-Type: ' . mime_content_type($path));
header('Content-Length: ' . filesize($path));

readfile($path);

这篇关于如何使用PHP从Web根目录外部提供文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆