PHP fileperms() Function

What is PHP fileperms() Function?

If you want to know the permission as a number of a file or folder, use fileperms() function. The function displays the number as octal value.

Syntax:

fileperms(filename)

Parameters:

The Function has 1 parameter which is required-

filename (Required): It is the path to the file or folder whose permission you want to get.

Return Values:

The function returns-

  • Permission number – if it successfully retrieves it.
  • FALSE – if it can’t return the permission.

Examples:

Example 1:

<?php
echo substr(sprintf("%o", fileperms("docs/dl.pdf")), -4);
?>

Output:

0666

Explanation:

The fileperms() function returns permission number. The sprints() function treats the permission number as a number and for the “%o” parameter it displays it as an octal number. And at last, the substr() function returns the last 4 digits (0666).

Example 2:

<?php
$perms = fileperms('docs/dl.pdf');
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;
?>

Output:

rrw-rw-rw-

CAUTION

  • PHP caches the information that it gets from fileperms() function. It could provide you wrong information for the subsequent call of this function. So, to clear the cache use clearstatcache() function.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP fileperms() Function

fileperms() is a very useful function to know permission of a file or directory. It is one of the built-in filesystem functions in PHP.

Reference:

https://www.php.net/manual/en/function.fileperms.php