Working with Permissions in PHP


PHP uses the same command as *nix systems when dealing with changing permissions for files:

chown – changes ownership, but can only be done by a root user
chgrp – changes group ownership, can be done by a user who is a member of the new group
chmod – changes permissions, can be done by the user (and sometimes the group) that owns the file

These commands are particularly useful in situations where PHP runs as a different user on the system, which is common when PHP is compiled as an Apache user. A lot of our customers get frustrated at the fact that once they use PHP to create a file, their user can’t touch it. That’s why whenever you have PHP create a file that needs to be neutral, its permissions have to be set accordingly.

The syntax of those commands are simple:

chown($file, $user)
chgrp($file, $group)
chmod($file, $permissions)

The simplest example of using these commands is a follows:

$file = "myfile.txt";
$handler = fopen($file, 'w') or die("can't create file");
chmod($file, '0777');
fclose($handler); ?>

In this example, I had the PHP script create a file called ‘myfile.txt’ in write mode, then change its permissions to 777.  This is of course the simplest example in the world, but you can make them much more complex.

For more information on using fopen to handle files, you can read this.  Also, when you set permissions you have to use the octal value (0777) instead of just 777.

Be Sociable, Share!

Leave a Reply

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