保護敏感 PHP 檔案(如設定檔、核心類別、API 端點)不被瀏覽器直接存取,是 Web 安全的基本功。本文整理三種常見且有效的防護手法。
<?php
$allowedReferer = "https://www.example.com/";
if (empty($_SERVER['HTTP_REFERER']) || strpos($_SERVER['HTTP_REFERER'], $allowedReferer) !== 0) {
header("Location: $allowedReferer");
exit;
}
// 正常邏輯...
缺點:Referer 可偽造、防火牆/隱私模式可能不送出,僅適合低風險頁面導引。
入口檔案 (index.php) 定義:
define('IN_SYSTEM', true);
受保護檔案 (config.php、core/*.php) 頂部驗證:
<?php
if (!defined('IN_SYSTEM')) {
header('HTTP/1.1 403 Forbidden');
exit('禁止直接存取');
}
所有框架(Laravel、ThinkPHP、CodeIgniter、Yii)皆採用此模式,簡單可靠。
public/index.php、靜態資源在 DocumentRoot專案結構範例:
/var/www/project/
├── app/ # 應用核心(不可直接存取)
├── config/ # 設定檔
├── vendor/ # Composer 套件
├── storage/ # 日誌、快取、上傳
└── public/ # DocumentRoot
├── index.php # 唯一入口
├── css/
└── js/
# 放在敏感目錄下
<Files "*.php">
Order Deny,Allow
Deny from all
</Files>
# 或僅允許特定 IP
<Files "admin.php">
Order Deny,Allow
Deny from all
Allow from 192.168.1.100
</Files>
display_errors、啟用錯誤日誌、定期掃描異常檔案「纏繞防禦」才是王道:單一機制皆可被突破,分層防護才能將風險降至最低。