不要使用 substr,請使用位元運算子
<?php
decoct(fileperms($file) & 0777); // 例如,傳回 "755"
?>
如果您要比較權限
<?php
0755 === (fileperms($file) & 0777);
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
fileperms — 取得檔案權限
filename
檔案路徑。
傳回檔案的權限,以數值模式表示。此模式的低位元與 chmod() 所預期的權限相同,但在大多數平台上,傳回值也會包含給定 filename
檔案類型的資訊。以下範例示範如何在 POSIX 系統(包括 Linux 和 macOS)上測試特定權限和檔案類型的傳回值。
對於本機檔案,特定的傳回值是 C 函式庫 stat() 函式所傳回結構的 st_mode
成員的值。設定的位元可能因平台而異,如果需要解析傳回值的非權限位元,建議查閱特定平台的文件。
失敗時傳回 false
。
失敗時,會發出 E_WARNING
。
範例 #1 以八進位值顯示權限
<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>
以上範例將輸出
1777 0644
範例 #2 顯示完整權限
<?php
$perms = fileperms('/etc/passwd');
switch ($perms & 0xF000) {
case 0xC000: // socket
$info = 's';
break;
case 0xA000: // symbolic link
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // block special
$info = 'b';
break;
case 0x4000: // directory
$info = 'd';
break;
case 0x2000: // character special
$info = 'c';
break;
case 0x1000: // FIFO pipe
$info = 'p';
break;
default: // unknown
$info = 'u';
}
// Owner
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));
// Group
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));
// World
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));
echo $info;
?>
以上範例將輸出
-rw-r--r--
注意:此函式的結果會被快取。詳情請參閱 clearstatcache()。
不要使用 substr,請使用位元運算子
<?php
decoct(fileperms($file) & 0777); // 例如,傳回 "755"
?>
如果您要比較權限
<?php
0755 === (fileperms($file) & 0777);
?>
有些人可能沒立刻注意到,但您可以使用 octdec( $octal_value ) 來比對 fileperms 取得的權限。
<?php
//假設檔案權限為 2770
$perm= fileperms( __FILE__ );
$bit = "102770";
printf( "%s\n", octdec( $bit ) );
printf( "%s\n", $perm);
?>
別忘記:clearstatcache();
==============================
每當您執行
mkdir($dstdir, 0770 ))
或是
chmod($dstdir, 0774 );
您必須呼叫
clearstatcache();
才能呼叫
fileperms($dstdir);
Windows 的檔案權限模型與 Unix 大不相同,且僅最低程度地整合它們。
以下是 Windows 計算位元遮罩的方式...
u+w/g+w/o+w 根據檔案是否具有唯讀旗標來設定。
u+r/g+w/o+w 永遠設定。
u+x/g+x/o+x 根據 $filename 是否為本身可執行的檔案(例如 bat)或目錄來設定。
Windows 完全沒有整合其 ACL。
所有這些的來源如下:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/stat-functions?view=vs-2019(但它沒有提供很多細節)