錯誤 `Warning: include(): failed to open stream: Permission denied` 表示 **PHP 進程用戶無權限讀取目標檔案/目錄**。本文提供 Linux/Windows 系統級排查步驟、權限模型說明、SELinux/AppArmor 隱形阻擋、最佳實踐配置。
Warning: include (/global.php): failed to open stream: Permission denied in index.php on line 21 Warning: include(): Failed opening '/global.php' for inclusion (include_path='.;C:\php5\pear') Fatal error: Class 'fl_global' not found
ps aux | grep -E 'php-fpm|httpd|apache' | head -5
# 典型輸出:www-data、nginx、apache、php-fpm
ls -la /path/to/global.php
# 輸出:-rw-r--r-- 1 root root 1234 Oct 10 10:00 global.php
# 其他用戶無讀取權(o-r) → 需 chmod o+r 或 chown www-data
namei -om /path/to/global.php
# 逐級顯示權限,找到缺 x 的目錄
# 假設 PHP 用戶為 www-data,代碼屬於 deploy 用戶組
chown -R deploy:www-data /var/www/html
find /var/www/html -type d -exec chmod 750 {} \;
find /var/www/html -type f -exec chmod 640 {} \;
# 關鍵:目錄 750 (u=rwx,g=rx,o=),檔案 640 (u=rw,g=r,o=)
# 若需寫入目錄(緩存、上傳):chmod 770 /var/www/html/var/cache
# 檢查上下文 ls -Z /var/www/html/global.php # 修正類型 semanage fcontext -a -t httpd_sys_content_t "/var/www/html(/.*)?" restorecon -Rv /var/www/html # 或暫時關閉(不建議生產) setenforce 0
<?php
// 測試腳本
$file = '/var/www/html/global.php';
echo "is_readable: " . (is_readable($file) ? 'YES' : 'NO') . "\n";
echo "fileperms: " . substr(sprintf('%o', fileperms($file)), -4) . "\n";
echo "process user: " . get_current_user() . "\n"; // 檔案擁有者
echo "exec user: " . exec('whoami') . "\n"; // 實際執行用戶
?>
#!/bin/bash
# deploy_perms.sh
WEB_ROOT="/var/www/html"
PHP_USER="www-data"
DEPLOY_USER="deploy"
DEPLOY_GROUP="www-data"
chown -R ${DEPLOY_USER}:${DEPLOY_GROUP} ${WEB_ROOT}
find ${WEB_ROOT} -type d -exec chmod 750 {} \;
find ${WEB_ROOT} -type f -exec chmod 640 {} \;
# 可寫目錄
for d in var/cache var/log public/uploads storage; do
[ -d "${WEB_ROOT}/${d}" ] && chmod 770 "${WEB_ROOT}/${d}"
done
# SELinux
command -v semanage &>/dev/null && {
semanage fcontext -a -t httpd_sys_content_t "${WEB_ROOT}(/.*)?"
semanage fcontext -a -t httpd_sys_rw_content_t "${WEB_ROOT}/var(/.*)?"
restorecon -Rv ${WEB_ROOT}
}
echo "Permissions applied."
權限問題 90% 是「目錄缺 x 權限」或「SELinux 標錯」。建立標準化部署腳本,一次配置、永久免維。