PHP: CHMOD a directory recursively

  • Post category:PHP
  • Post comments:0 Comments

The script below loops over the specified directory and chmods its files, directories and subdirectories recursively.

<?php

  function chmodDirectory( $path = '.', $level = 0 ){  
  $ignore = array( 'cgi-bin', '.', '..' ); 
  $dh = @opendir( $path ); 
  while( false !== ( $file = readdir( $dh ) ) ){ // Loop through the directory 
  if( !in_array( $file, $ignore ) ){

        if( is_dir( "$path/$file" ) ){

          chmod("$path/$file",0755);

          chmodDirectory( "$path/$file", ($level+1));

        } else {

          chmod("path/$file",0644); // desired permission settings

        }//elseif 
	}//if in array 
	}//while 
	
	closedir( $dh ); 
	}//function
	chmodDirectory("the_directory/",0);

?>