In PHP, files from a folder can be deleted using various approaches and inbuilt methods such as unlink, DirectoryIterator and DirectoryRecursiveIterator.
Some of these approaches are explained below:
Approach 1:
- Generate a list of files using glob() method
- Iterate over the list of files.
- Check whether the name of files is valid.
- Delete the file using unlink() method.
Example:
<?php
$folder_path = "myGeeks" ;
$files = glob ( $folder_path . '/*' );
foreach ( $files as $file ) {
if ( is_file ( $file ))
unlink( $file );
}
?>
|
Output:
Before Running the code:

After Running the code:

Note: Hidden files can be included in the file removal operation by addition of the below code:
$hidden_files = glob ( $folder_path . '/{, .}*' , GLOB_BRACE);
|
Approach 2:
Example:
<?php
array_map ( 'unlink' , array_filter (
( array ) array_merge ( glob ( "myGeeks/*" ))));
?>
|
Approach 3:
- Generate list of files using DirectoryIterator.
- Iterate over the list of files.
- Validate the file while checking if the file directory has a dot or not.
- Using the getPathName method reference, delete the file using unlink() method.
Example:
<?php
$folder_path = 'myGeeks/' ;
$dir = new DirectoryIterator(dirname( $folder_path ));
foreach ( $dir as $fileinfo ) {
if (! $fileinfo ->isDot()) {
unlink( $fileinfo ->getPathname());
}
}
?>
|
Approach 4:
Example:
<?php
$dir = "myGeeks/" ;
$dir = new RecursiveDirectoryIterator(
$dir , FilesystemIterator::SKIP_DOTS);
$dir = new RecursiveIteratorIterator(
$dir ,RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $dir as $file ) {
$file ->isDir() ? rmdir ( $file ) : unlink( $file );
}
?>
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Jan, 2019
Like Article
Save Article