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

I have files in different formats: ePub/mobi/pdf/etc.

But I don't want anyone to access those files and certain files cannot be access by some users. So I cannot use HTTP to protect the folder that contains the files because it might give access to one user to all the files...

So is there a PHP function that can get a file from a folder that cannot be access publicly to then send it back to the user?

Thanks in advance!

Just store the file out of the root directory that holds all of your front-facing files. So assuming your directory structure is as such:

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

Then, just grab your file with a relative path (here is an example pulled from 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;
    }
?>

You may have to configure open_basedir for PHP to open a file outside of the web root.

Yes. Look at fpassthru() and use it like this:

$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);