Code Examples

Here's a few simple code examples for changing file and directory permissions programatically.

Chmod with PHP

Format:

bool chmod( string $path, int $mode);

Note: in PHP that the mode must be supplied as octal so always prefix with 0. For more info see http://php.net/manual/en/function.chmod.php.

<?php
chmod("/somedir/somefile", 755);   // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755);  // octal; correct value of mode
?>
<?php
// SGID bit set, Everything for user, and group and read and exec
// for other
chmod("/somedir/somefile", 02775);
?>

Chmod with Python

Format:

os.chmod(path, mode)

In python it's possible to use octal values or use values defined in the stat module. For more info see http://docs.python.org/library/os.html#os.chmod.

import os

# Everything for user and group and read and exec for other
os.chmod("/somedir/somefile", 0775)

# SGID bit set. Everything for user and group and read and exec for other
os.chmod("/somedir/somefile", 02775)

Chmod with Ruby

Format:

chmod(mode, *files)

Changes permission bits on files to the bit pattern represented by mode. If the last parameter isn‘t a String, verbose mode will be enabled.

File.chmod 0755, 'somecommand'
File.chmod 0644, 'my.rb', 'your.rb', true