Master PHP fileperms(): Retrieve and Decode File Permissions Easily
This guide explains how to use PHP's fileperms() function to obtain a file's permission bits, interprets the returned integer with bitwise operations, and provides a helper format_perms() routine that converts the raw value into the familiar symbolic permission string such as -rw-r--r--.
Summary
In PHP development you can obtain a file's permission bits using the built-in fileperms() function. The function accepts a file path string and returns an integer where the low 9 bits represent read, write and execute permissions for owner, group and others.
A simple example:
<?php
$filename = 'test.txt';
$perms = fileperms($filename);
echo "File {$filename} permissions: {$perms}";
?>The returned integer can be converted to the familiar symbolic string (e.g. -rw-r--r--) by applying bitwise masks. The article provides a helper format_perms() function that checks the various bits (0xC000, 0xA000, etc.) and builds the permission string.
<?php
function format_perms($perms) {
$result = '';
if (($perms & 0xC000) == 0xC000) { $result .= 's'; }
elseif (($perms & 0xA000) == 0xA000) { $result .= 'l'; }
elseif (($perms & 0x8000) == 0x8000) { $result .= '-'; }
elseif (($perms & 0x6000) == 0x6000) { $result .= 'b'; }
elseif (($perms & 0x4000) == 0x4000) { $result .= 'd'; }
elseif (($perms & 0x2000) == 0x2000) { $result .= 'c'; }
elseif (($perms & 0x1000) == 0x1000) { $result .= 'p'; }
else { $result .= 'u'; }
$result .= ($perms & 0x0100) ? 'r' : '-';
$result .= ($perms & 0x0080) ? 'w' : '-';
if ($perms & 0x0040) {
$result .= ($perms & 0x0800) ? 's' : 'x';
} else {
$result .= ($perms & 0x0800) ? 'S' : '-';
}
$result .= ($perms & 0x0020) ? 'r' : '-';
$result .= ($perms & 0x0010) ? 'w' : '-';
if ($perms & 0x0008) {
$result .= ($perms & 0x0400) ? 't' : 'x';
} else {
$result .= ($perms & 0x0400) ? 'T' : '-';
}
$result .= ($perms & 0x0004) ? 'r' : '-';
$result .= ($perms & 0x0002) ? 'w' : '-';
$result .= ($perms & 0x0001) ? 'x' : '-';
return $result;
}
$filename = 'test.txt';
$perms = fileperms($filename);
$formatted_perms = format_perms($perms);
echo "File {$filename} permissions: {$formatted_perms}";
?>Running the script prints something like File test.txt permissions: -rw-r--r--, demonstrating how to read and format file permissions in PHP.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
