首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 取得檔案權限的實用函式:fileperms 與 base_convert 應用

     編輯:PHP 相關知識

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

權限碼對照表

八進位二進位權限含義
0000--- 無權限
1001--x 僅執行
2010-w- 僅寫入
3011-wx 寫入+執行
4100r-- 唯讀
5101r-x 讀取+執行
6110rw- 讀取+寫入
7111rwx 完整權限

進階:解析完整權限(含檔案類型與特殊位)

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'
  • 安全稽核掃描全站權限異常檔案(如 0777、含 setuid 的非系統檔)
  • 安裝精靈檢查 storage/、bootstrap/cache/ 等目錄權限
  • 檔案上傳後自動 chmod 至安全權限

掌握 fileperms + base_convert 技巧,能快速編寫權限檢查工具,提升部署與安全維運效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved