UnkwnTech
UnkwnTech

Reputation: 90961

Check file permissions

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

Upvotes: 18

Views: 23857

Answers (6)

Doru
Doru

Reputation: 1

decoct(fileperms($dir) & 0777) to get file permission. Example: var_dump(decoct(fileperms($dir) & 0777)); //return is '755'

Upvotes: 0

Maciej Sz
Maciej Sz

Reputation: 12045

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 );
}

Upvotes: 7

OzzyCzech
OzzyCzech

Reputation: 10412

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

Upvotes: 1

Željko Živković
Željko Živković

Reputation: 4438

Use fileperms() function

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

Upvotes: 23

Huppie
Huppie

Reputation: 11432

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

Upvotes: 12

Chris Hanson
Chris Hanson

Reputation: 55174

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.

Upvotes: 0

Related Questions