除了从根目录删除文件之外,如果您正在运行 apache,您还可以更改.htaccess
(我确信基于 Windows 的系统有一个web.config
相等的)禁止直接访问某些文件。如果您将此代码片段添加到该文件中,它将拒绝带有以下内容的文件.pdf
扩大:
<FilesMatch "\.(pdf)$">
Order Allow,Deny
Deny from all
</FilesMatch>
从那里,在您的应用程序内部,您可以创建某种系统来管理 PDF 链接,因此,如果您将真实路径存储在数据库中并使用 id 作为链接,类似于:
http://www.example.com/?file=1
或者如果您只是进行简单的扫描:
<?php
# The folder that the PDFs are in
$dir = __DIR__.'/website/folder/';
# Loop over a scan of the directory (you can also use glob() here)
foreach(scandir($dir) as $file):
# If file, create a link
if(is_file($dir.$file)): ?>
<a href="?action=download&file=<?php echo $file ?>"><?php echo $file ?></a>
<?php
endif;
endforeach;
然后,如果用户尝试使用链接下载,您将检查他们是否首先登录,如果是,则在将其他任何内容输出到浏览器之前,通过执行如下脚本来下载文件(包括空格):
<?php
session_start();
# First check that the user is logged in
if(empty($_SESSION['username']))
die('You must be logged in to download this document.');
# Not sure which directory you are currently in, so I will assume root
# I would do basename() here incase the user tries to add in something like:
# ../index.php and tries to download files they are not supposed to
$file = __DIR__.'/website/folder/'.basename($_GET['file']);
if(!is_file($file))
die('File does not exist.');
# Double check that the file is a pdf
elseif(strtolower(pathinfo($file, PATHINFO_EXTENSION)) != 'pdf')
die('File appears to be invalid.');
# Start download headers
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;