本文目录导读:

在PHP项目中限制目录访问权限,可以通过以下几种方法实现:
Web服务器配置(最常用)
Apache (.htaccess)
# 禁止访问所有文件
Deny from all
# 或者拒绝特定IP
Order Deny,Allow
Deny from all
Allow from 192.168.1.0/24
# 允许访问特定文件
<Files "index.php">
Allow from all
</Files>
Nginx
# 禁止访问目录
location /admin/ {
deny all;
# 允许特定IP
allow 192.168.1.0/24;
}
# 禁止访问敏感文件
location ~ \.(env|sql|log|json)$ {
deny all;
return 404;
}
# 禁止访问 .git 目录
location ~ /\.(git|svn|ht) {
deny all;
}
PHP 权限控制
基于角色的访问控制
<?php
session_start();
class AccessControl {
private $userRoles = [];
public function checkAccess($requiredDir) {
// 检查用户是否登录
if (!isset($_SESSION['user_id'])) {
header('HTTP/1.0 403 Forbidden');
die('需要登录才能访问');
}
// 检查用户角色权限
$userRole = $_SESSION['user_role'];
// 定义目录权限映射
$permissions = [
'admin' => ['admin', 'super_admin'],
'uploads' => ['user', 'admin', 'super_admin'],
'api' => ['api_access']
];
if (!in_array($userRole, $permissions[$requiredDir] ?? [])) {
header('HTTP/1.0 403 Forbidden');
die('没有访问权限');
}
}
}
// 使用示例
$access = new AccessControl();
$access->checkAccess('admin');
?>
入口文件控制
<?php
// index.php - 统一的入口文件
define('IN_APP', true);
// 定义安全目录列表
define('ALLOWED_DIRS', ['public', 'api', 'admin']);
class Router {
public function handleRequest() {
$uri = $_SERVER['REQUEST_URI'];
$path = parse_url($uri, PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));
$directory = $segments[0] ?? '';
// 检查是否在允许的目录中
if (!in_array($directory, explode(',', ALLOWED_DIRS))) {
header('HTTP/1.0 404 Not Found');
exit('页面不存在');
}
}
}
文件系统权限
目录权限设置
# 设置目录权限(Linux) chmod 755 /var/www/html/uploads # 755: 目录可读写执行 chmod 644 /var/www/html/config.php # 644: 文件只读 # 设置所有者 chown www-data:www-data /var/www/html # 敏感目录设置为700 chmod 700 /var/www/html/private
PHP 文件权限检查
<?php
class FilePermission {
public function checkDirectoryAccess($dir) {
$safeDirs = [
'/var/www/html/uploads',
'/var/www/html/temp'
];
$realPath = realpath($dir);
// 检查是否在安全目录内
$allowed = false;
foreach ($safeDirs as $safeDir) {
if (strpos($realPath, realpath($safeDir)) === 0) {
$allowed = true;
break;
}
}
if (!$allowed) {
header('HTTP/1.0 403 Forbidden');
die('目录访问被拒绝');
}
}
}
?>
配置文件保护
数据库配置文件示例
<?php
// config/database.php - 放在Web根目录外
return [
'host' => 'localhost',
'dbname' => 'myapp',
'username' => 'appuser',
'password' => 'secure_password123'
];
// 在入口文件包含
require_once __DIR__ . '/../config/database.php';
.env 文件保护
# .htaccess
<Files .env>
Order allow,deny
Deny from all
</Files>
综合安全配置示例
项目结构
project/
├── public/ # Web根目录
│ ├── index.php
│ ├── .htaccess
│ └── assets/
├── private/ # 私有目录
│ ├── config/
│ ├── includes/
│ └── logs/
├── uploads/ # 上传目录
└── vendor/
完整的 .htaccess 配置
# 防止目录列表
Options -Indexes
# 禁止访问敏感文件
<FilesMatch "\.(env|json|config|sql|log|ini)$">
Order allow,deny
Deny from all
</FilesMatch>
# 禁止访问隐藏文件
<FilesMatch "^\.">
Order allow,deny
Deny from all
</FilesMatch>
# 只允许 index.php 访问
RewriteEngine On
RewriteRule ^(?!index\.php|assets/).*$ index.php [L,QSA]
最佳实践建议
- 分层防护:结合服务器配置和PHP逻辑双重检查
- 最小权限原则:只给予必要的访问权限
- 日志记录:记录所有访问尝试
- 定期审计:检查目录权限配置
- 敏感文件位置:将配置文件放在Web根目录外
通过这些方法,可以有效保护PHP项目的目录安全,防止未授权访问。