所有文件只能通过index.php下载,并拒绝从浏览器直接访问



我的网站中有以下结构:

  • index.php
  • 文件(目录(--->文件1.pdf

如何防止直接访问文件(例如https://example.com/files/file1.pdf)并允许从显示的网页内为登录用户下载文件?

以下是索引的php代码,该索引从以下目录中读取文件:

<?php
include('session.php');
$path    = './files';
$files = scandir($path);
$files = preg_grep("/^(.|..|index.php|.htaccess)$|.php$|.meta.js$/",scandir($path), PREG_GREP_INVERT);
foreach($files as $file){
echo '<div>';
echo "<a href='$file' >$file</a>";
echo "</div>";
}
?>
  1. 在文件中创建.htaccess并设置deny-all。

    订单拒绝、允许拒绝所有

  2. 创建downloader.php并更新您的下载链接URL,如

domain.com/downloader.php?file=文件名

代码:

<?php 
if(!isset($_GET['file']))
{
die('File Request Not found.');
}
if(!file_exists('files/'.$_GET['file']))
{
die('File not exists. File name ='.$_GET['file']);
}
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename="".$_GET['file']."""); 
echo readfile('files/'.$_GET['file']);
?>

AddHandler application/x-httpd-php .html
<FilesMatch ".(?i:gif|jpe?g|png)$">
order deny,allow
Deny from all
</FilesMatch>

用法=这些规则将允许您仅从index.html下载文件,并拒绝从浏览器直接访问这些文件。

下面是我如何解决这个问题的:

在.htaccess中添加了规则:

<FilesMatch ".(?i:pdf|jpe?g|png)$">
order deny,allow
Deny from all
</FilesMatch>

所以现在没有人可以通过浏览器的直接链接访问这些文件。

然后在downloader.php中添加了以下代码(当然,仍然需要链接到会话才能只允许登录用户(:

<?php
if(isset($_GET['path']))
{
//Read the filename
$filename = $_GET['path'];
//Check the file exists or not
if(file_exists($filename)) {
//Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
//Clear system output buffer
flush();
//Read the size of the file
readfile($filename);
//Terminate from the script
die();
}
else{
echo "File does not exist.";
}
}
else
echo "Filename is not defined."
?>

并对index.php:做了一些更改

echo "<a href=./downloader.php?path='$pathOF/$file' class='pdfl'>$file</a>";

一切都很好,只是请求下载文件时有一点延迟,可能是主机问题,也可能是下载者不确定,请告诉我是否有更好的方法。

问候

相关内容

最新更新