PHP 內建 fileperms() 回傳檔案權限的十進位整數,直接閱讀不直觀。結合 base_convert() 轉八進位並截取後四位,即可獲得熟悉的 0755、0644 格式權限碼。
<?php
/**
* 取得檔案權限(八進位字串,如 0755、0644)
* @param string $filepath 檔案路徑
* @return string|false 權限字串或 false(檔案不存在/無權限)
*/
function getChmod($filepath) {
// fileperms 回傳十進位整數,含檔案類型位元
// base_convert(..., 10, 8) 轉八進位
// substr(..., -4) 取最後四位(所有者/群組/其他權限)
return substr(base_convert(@fileperms($filepath), 10, 8), -4);
}
// 使用範例
echo getChmod("/var/www/html/index.php"); // 輸出如:0644
echo getChmod("/var/www/html/storage"); // 輸出如:0755
?>
fileperms():回傳 stat 結構的 st_mode 欄位(十進位),包含檔案類型(目錄/一般檔/連結等)與權限位元base_convert($num, 10, 8):十進位轉八進位字串substr($str, -4):取右側 4 字元,對應 rwx 三組權限(每組 3 位)+ 1 位特殊位(setuid/setgid/sticky)@ 抑制警告:檔案不存在時回傳 false,base_convert 會產生警告,@ 讓函式靜默回傳 false| 八進位 | 二進位 | 權限含義 |
|---|---|---|
| 0 | 000 | --- 無權限 |
| 1 | 001 | --x 僅執行 |
| 2 | 010 | -w- 僅寫入 |
| 3 | 011 | -wx 寫入+執行 |
| 4 | 100 | r-- 唯讀 |
| 5 | 101 | r-x 讀取+執行 |
| 6 | 110 | rw- 讀取+寫入 |
| 7 | 111 | rwx 完整權限 |
function getFullPerms($filepath) {
$perms = @fileperms($filepath);
if ($perms === false) return false;
$info = [];
$info['octal'] = decoct($perms);
$info['type'] = [
0xC000 => 'socket',
0xA000 => 'symlink',
0x8000 => 'file',
0x6000 => 'block',
0x4000 => 'dir',
0x2000 => 'char',
0x1000 => 'fifo',
][$perms & 0xF000] ?? 'unknown';
$info['special'] = [];
if ($perms & 0x800) $info['special'][] = 'setuid';
if ($perms & 0x400) $info['special'][] = 'setgid';
if ($perms & 0x200) $info['special'][] = 'sticky';
$info['owner'] = ($perms >> 6) & 7;
$info['group'] = ($perms >> 3) & 7;
$info['other'] = $perms & 7;
return $info;
}
print_r(getFullPerms("/var/www/html/index.php"));
/*
Array
(
[octal] => 100644
[type] => file
[special] => Array()
[owner] => 6
[group] => 4
[other] => 4
)
*/
getChmod($dir) >= '0755'storage/、bootstrap/cache/ 等目錄權限chmod 至安全權限掌握 fileperms + base_convert 技巧,能快速編寫權限檢查工具,提升部署與安全維運效率。