PHP 8.5.0 Alpha 1 available for testing

Voting

: four plus five?
(Example: nine)

The Note You're Voting On

anonymous_user
4 years ago
// Recursive PHP function to completely remove a directory

function delete_directory_recursively( $path ) {

$dir = new \DirectoryIterator( $path );

// Iterate through the subdirectories / files of the provided directory
foreach ( $dir as $dir_info ) {

// Exclude the . (current directory) and .. (parent directory) paths
// from the directory iteration
if ( ! $dir_info->isDot() ) {

// Get the full currently iterated path
$iterated_path = $dir_info->getPathname();

// If the currently iterated path is a directory
if ( $dir_info->isDir() ) {

// which is not empty (in which case scandir returns an array of not 2 (. and ..) elements)
if ( count( scandir( $iterated_path ) ) !== 2 ) {

// Call the function recursively
self::remove_directory_recursively( $iterated_path );

} else {

// if the currently iterated path is an empty directory, remove it
rmdir( $iterated_path );

}

} elseif ( $dir_info->isFile() ) {

// If the currently iterated path describes a file, we need to
// delete that file
unlink( $iterated_path );

}

} // loop which opens if the currently iterated directory is neither . nor ..

} // end of iteration through directories / files of provided path

// After iterating through the subpaths of the provided path, remove the
// concerned path
rmdir( $path );

} // end of delete_directory_recursively() function definition

<< Back to user notes page

To Top