![](/img/trans.png)
[英]Restrict direct access to .php files through browser and allow only index.php to access them
[英]All files download only through index.php and deny direct access to them from browser
我的網站有以下結構:
如何防止直接訪問文件(例如https://example.com/files/file1.pdf )並允許從顯示的 Z2567A5EC9705EB7AC2C984033E061 頁面中下載文件登錄用戶?
這是從目錄中讀取文件的索引的 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>";
}
?>
在文件中創建一個 .htaccess 並設置全部拒絕。
命令拒絕,允許所有人拒絕
創建 downloader.php 並更新您的下載鏈接網址,例如
domain.com/downloader.php?file=filename
代碼:
<?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>
所以現在沒有人可以通過瀏覽器的直接鏈接訪問這些文件。
然后將以下代碼添加到下載器中。php (當然仍然需要鏈接到 session 以僅允許登錄用戶):
<?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>";
一切正常,請求文件下載時只是有點延遲,可能是主機問題或者可能是下載器不確定,如果有更好的方法,請告訴我。
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.