[英]How to prevent direct access to files in folder?
有一個網頁,其中的“ subdir”具有以下結構:
index.php在/ system中調用file1.php。 然后/ system中的其他文件被“提交”調用。 我無法編寫正確的.htaccess來防止直接通過其URL調用這些/ system / 。
我用谷歌搜索並嘗試了各種.htaccess內容。 但是大多數情況下, “ subdir”根本無法訪問(甚至不能從index.php ),或者“ webpage”訪問返回“ 404” 。
通常,用戶應打開index.php並決定要執行的操作。 依賴於此,他被重定向到相應的/ system / .php。 任何其他嘗試/例如添加https:// mywebpage / subdir / system / anyfile 。 應將他重定向回index.php或任何其他“錯誤頁面”。
典型的方法是在入口點(如index.php)中定義一個先於其他文件運行的全局常量,然后檢查每個文件是否定義了該常量
define('SOME_CONST', true);
然后在每個文件的頂部
if(!defined('SOME_CONST')) die ("No direct access");
因此在不首先加載定義常量的文件的情況下訪問文件將導致PHP終止。
這個“常量”可以是任何東西,通常我使用相對於index.php文件等的基本路徑。
define('MY_BASE_PATH', __DIR__.'/');
等等...
注意事項
我應該提到您不應該在文件中定義它並將其包含在其他文件中,否則它將無法正常工作。
//DO NOT DO THIS as IT wont WORK!!!!! - technically it never fails
//--- in the file somefile.php ---
//required file defines SOME_CONST
require 'index.php';
//define('SOME_CONST', true); -- defined in index.php, think of it like copy and pasting that files code at this spot.
//will never fail, because it's defined by the file included/required above
if(!defined('SOME_CONST')) die ("No direct access");
這就像將其放入您的代碼中並期望它會失敗(顯然,這里永遠不會失敗):
//dont do this either
define('SOME_CONST', true);
if(!defined('SOME_CONST')) die ("No direct access");
而是這樣做:
因此,您必須包括該入口點的文件,並使用路由器等...基本的MVC。 改為這樣做(大大簡化了)
// --- in index.php ---
define('SOME_CONST', true);
require 'somepage.php';
//if(!defined('SOME_CONST')) die ("No direct access"); included in the above require
接着
//--- in somefile.php ---
if(!defined('SOME_CONST')) die ("No direct access"); //will fail if index.php is not loaded.
因此,如果有人只訪問somefile.php
該常量未定義。 因為沒有在該文件“之前”執行index.php
。...如果您在檢查之前包括index.php
(在somefile.php
),則不喜歡。 您顯然不能在檢查后包括它( index.php
)。 因此它必須在somefile.php
之前運行,而不是僅在加載somefile.php
時運行。 這就是為什么您不能在somefile.php
包含index.php
,而必須在index.php
包含somefile.php
的原因。
同樣顯然,您將需要多於一頁的somefile.php
。 因此,在索引中,您將需要一種將請求定向到正確頁面的方法。 這稱為路由。 這是另一個主題...
我試圖使它盡可能基本。 這真的很簡單。
請享用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.