chmod syntax code example

Example 1: chmod usage

The three rightmost digits define permissions for the:
file user, the group, and others. 

Example usage: sudo chmod 777 testfile.txt

#	Permission				rwx	Binary
7	read, write and execute	rwx	111
6	read and write			rw-	110
5	read and execute		r-x	101
4	read only				r--	100
3	write and execute		-wx	011
2	write only				-w-	010
1	execute only			--x	001
0	none					---	000

Example 2: chmod

chmod u=rwx,g=rx,o=r myfile

chmod 754 myfile

# 4 stands for "read",
# 2 stands for "write",
# 1 stands for "execute", and
# 0 stands for "no permission."

Example 3: change mode in linux

For changing permissions mode of files as "file.exe" follow next examples idea:
chmod file.exe ugo+x #Add x:execute permissions to u:user g:gropu and o:others
chmod file.exe o-rw  #Remove r:read and w:write permissions to o:others
chmod file.exe +rwx  #Add all r:read, w:wirte and x:execute permissions to all.

Example 4: running chmod command using code

private function chmod_r($dir, $permission)
{
  $dp = opendir($dir);

  while($file = readdir($dp))
  {
    if (($file == ".") || ($file == "..")) continue;

    $path = $dir . DIRECTORY_SEPARATOR . $file;
    $is_dir = is_dir($path);

    $this->set_perms($path, $is_dir, $permission);
    if($is_dir) {
    	$this->chmod_r($path, $permission);
    }
  }
  closedir($dp);
}

private function set_perms($file, $is_dir, $permission)
{
  $perm = substr(sprintf("%o", fileperms($file)), -4);
  $dirPermissions = $permission;
  $filePermissions = $permission;

  if($is_dir && $perm != $dirPermissions){
  	chmod($file, octdec($dirPermissions));
  }
  else if(!$is_dir && $perm != $filePermissions){
  chmod($file, octdec($filePermissions));
  }

  flush();
}

$permission = '0777';

$dir = storage_path('framework');

$this->chmod_r($dir, $permission);

Tags:

Misc Example