什么是最好的PHP函数来获得隐藏在后端的文件


What is the best PHP function to get a file hidden in the backend?

我有不同格式的文件:ePub/mobi/pdf/等。

但我不希望任何人访问这些文件,某些用户无法访问某些文件。所以我不能使用HTTP来保护包含文件的文件夹,因为它可能会让一个用户访问所有文件。。。

那么,有没有一个PHP函数可以从无法公开访问的文件夹中获取文件,然后将其发送回用户?

提前感谢!

只需将文件存储在包含所有前端文件的根目录之外。所以假设你的目录结构是这样的:

root
-- public_html
-- -- access_book.php
-- -- index.php
-- -- ...
-- books
-- -- mobi_dick.pdf
-- -- ...

然后,只需获取具有相对路径的文件(这里是从readfile中提取的一个示例):

<?php
    // Replace this with the path to the actual file
    $file = '../books/mobi_dick.pdf';
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
?>

您可能需要为PHP配置open_basedir才能在web根目录之外打开文件。

是。查看fpassthru()并像这样使用它:

$mime_type = 'image/jpg'; // or whatever
$file_name = '/private/some.jpg'; // or whatever
// TODO: add check for If-Modified-Since or ETag HTTP header and handle appropriately
if (($fp = fopen($file_name, 'r')) === false)
{
    header("HTTP/1.0 404 Not Found");
    exit(0);
}
header('Content-Type: ' . $mime_type);
header('Content-Length: ' . filesize($file_name));
fpassthru($fp);
fclose($fp);