php – Check file permissions-ThrowExceptions

Exception or error:

How can I check file permissions, without having to run operating system specific command via passthru() or exec()?

How to solve:

Use fileperms() function

echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);


You can use the is_readable(), is_executable() etc.. commands.


Real coders use bitwise operations, not strings 😉 This is much more elegant way of handling permissions:

function checkPerms($path)
    clearstatcache(null, $path);
    return decoct( fileperms($path) & 0777 );


Use fileperms() function and substring:

substr(decoct(fileperms(__DIR__)), -4); // 0777
substr(decoct(fileperms(__DIR__)), -3); // 777

For file:

substr(decoct(fileperms(__FILE__)), -4); // 0644
substr(decoct(fileperms(__FILE__)), -3); // 644

Replace __FILE__ and __DIR__ with your path or variable


What do you want to do by checking file permissions?

When writing secure code, it’s almost always incorrect to “check, then do” anything. The reason is that between the checking whether you can do something and actually doing it, the state of the system could change such that doing it would have a different result.

For example, if you check whether a file exists before writing one, don’t check whether you wrote the file successfully (or don’t check in a detailed-enough fashion), and then later depend on the contents of the file you wrote, you could actually be reading a file written by an attacker.

So instead of checking file permissions, just do whatever it was you were going to do if the permissions check succeeded, and handle errors gracefully.

Leave a Reply

Your email address will not be published. Required fields are marked *