Delete files and folder php

PHP: Delete all files from a folder.

In this guide, we are going to show you how to delete all files in a folder using PHP.

Our first example is pretty straight-forward, as we simply loop through the files and then delete them.

Take a look at the following code sample.

//The name of the folder. $folder = 'temporary_files'; //Get a list of all of the file names in the folder. $files = glob($folder . '/*'); //Loop through the file list. foreach($files as $file) < //Make sure that this is a file and not a directory. if(is_file($file))< //Use the unlink function to delete the file. unlink($file); >>
  1. In this example, we will be deleting all files from a folder called “temporary_files”.
  2. We list the files in this directory by using PHP’s glob function. The glob function basically finds pathnames that match a certain pattern. In this case, we use a wildcard (asterix) to specify that we want to select everything that is inside the “temporary_files” folder.
  3. The glob function returns an array of file names that are in the specified folder.
  4. We then loop through this array.
  5. Using the is_file function, we check to see if it is a file and not a parent directory or a sub-directory.
  6. Finally, we use the unlink function, which deletes the file.

Deleting files in sub-folders.

To delete all files and directories in all sub-directories, we can use recursion.

Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.

function deleteAll($str) < //It it's a file. if (is_file($str)) < //Attempt to delete it. return unlink($str); >//If it's a directory. elseif (is_dir($str)) < //Get a list of the files in this directory. $scan = glob(rtrim($str,'/').'/*'); //Loop through the list of files. foreach($scan as $index=>$path) < //Call our recursive function. deleteAll($path); >//Remove the directory itself. return @rmdir($str); > > //call our function deleteAll('temporary_files');

The function above basically checks to see if the $str variable represents a path to a file. If it does represent a path to a file, it deletes the file using the function unlink.

Читайте также:  Javascript кнопка со ссылкой

However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one.

Finally, it removes the sub-directory itself by using PHP’s rmdir function.

Источник

rmdir

Attempts to remove the directory named by directory . The directory must be empty, and the relevant permissions must permit this. A E_WARNING level error will be generated on failure.

Parameters

Return Values

Returns true on success or false on failure.

Examples

Example #1 rmdir() example

See Also

  • is_dir() — Tells whether the filename is a directory
  • mkdir() — Makes directory
  • unlink() — Deletes a file

User Contributed Notes 29 notes

Glob function doesn’t return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

public static function delTree ( $dir ) <
$files = array_diff ( scandir ( $dir ), array( ‘.’ , ‘..’ ));
foreach ( $files as $file ) <
( is_dir ( » $dir / $file » )) ? delTree ( » $dir / $file » ) : unlink ( » $dir / $file » );
>
return rmdir ( $dir );
>
?>

The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy.

Never ever use jurchiks101 at gmail dot com code. It contains command injection vulnerability.
If you want to do it that way, use something like this instead:

if ( PHP_OS === ‘Windows’ )
exec ( sprintf ( «rd /s /q %s» , escapeshellarg ( $path )));
>
else
exec ( sprintf ( «rm -rf %s» , escapeshellarg ( $path )));
>
?>

Note the escapeshellarg usage to escape any possible unwanted character, this avoids putting commands in $path variable so the possibility of someone «pwning» the server with this code

some implementations of recursive folder delete don’t work so well (some give warnings, other don’t delete hidden files etc).

function rrmdir ( $src ) $dir = opendir ( $src );
while( false !== ( $file = readdir ( $dir )) ) if (( $file != ‘.’ ) && ( $file != ‘..’ )) $full = $src . ‘/’ . $file ;
if ( is_dir ( $full ) ) rrmdir ( $full );
>
else unlink ( $full );
>
>
>
closedir ( $dir );
rmdir ( $src );
>

I was working on some Dataoperation, and just wanted to share an OOP method with you.

It just removes any contents of a Directory but not the target Directory itself! Its really nice if you want to clean a BackupDirectory or Log.

Also you can test on it if something went wrong or if it just done its Work!

I have it in a FileHandler class for example, enjoy!

public function deleteContent ( $path ) try $iterator = new DirectoryIterator ( $path );
foreach ( $iterator as $fileinfo ) if( $fileinfo -> isDot ())continue;
if( $fileinfo -> isDir ()) if( deleteContent ( $fileinfo -> getPathname ()))
@ rmdir ( $fileinfo -> getPathname ());
>
if( $fileinfo -> isFile ()) @ unlink ( $fileinfo -> getPathname ());
>
>
> catch ( Exception $e ) // write log
return false ;
>
return true ;
>

Another simple way to recursively delete a directory that is not empty:

itay at itgoldman’s function falls into an infinite loop if the $src directory doesn’t exist.
Here’s a fix — one should do at least a file_exists() check before the loop:

Thanks to itay for the original function, though, it was helpful.

Say, you’re working on Windows and continue to get a permission’s error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can’t find that program, the line

may solve the problem!
Make sure to write this before rmdir($dirname);.

I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.

This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get «stuck» and throw permissions errors. I was not able to delete them with PHP or in windows itself. The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own. Disabling the wincachce module resolved the issue.

I’ve noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO. if you get a permissions error and there shouldn’t be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.

It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

public static function delTree ( $dir ) <
$files = array_diff ( scandir ( $dir ), array( ‘.’ , ‘..’ ));
foreach ( $files as $file ) <
( is_dir ( » $dir / $file » ) && ! is_link ( $dir )) ? delTree ( » $dir / $file » ) : unlink ( » $dir / $file » );
>
return rmdir ( $dir );
>
?>

Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle))

if a folder named 0 (zero) is found during traversing the hierarchy

Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec(‘rmdir folder-to-delete /s /q’); //windows
exec(‘rmdir -rf folder-to-delete’); //OS X/*nix?

function unlinkDir($dir)
$dirs = array($dir);
$files = array() ;
for($i=0;;$i++)
if(isset($dirs[$i]))
$dir = $dirs[$i];
else
break ;

if($openDir = opendir($dir))
while($readDir = @readdir($openDir))
if($readDir != «.» && $readDir != «..»)

foreach($files as $file)
unlink($file) ;

>
$dirs = array_reverse($dirs) ;
foreach($dirs as $dir)
rmdir($dir) ;
>

Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
if (is_dir($dir))
<
$files = scandir($dir);
foreach ($files as $file)
<
if ($file != «.» && $file != «..»)
<
if (filetype($dir.»/».$file) == «dir»)
$this->deletedir($dir.»/».$file);
>
else
unlink($dir.»/».$file);
>
>
>
reset($objects);
if(rmdir($dir))
return ‘deleted successfully!’;
>
else
return ‘delete failed!’;
>
>
else
return ‘doesn\’t exist or inaccessible!’;
>
>
Something to note:
You have to take care of file permission if necessary

it Will Delete All Fildes in folder and that folder too.

echo $path = ‘D:\xampp\htdocs\New folder\New folder’;

function rmdir_recursive($dir) $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($it as $file) if ($file->isDir()) rmdir($file->getPathname());
else unlink($file->getPathname());
>
rmdir($dir);
>
rmdir_recursive($path);

A patch to previous script to make sure rights for deletion is set:

//Delete folder function
function deleteDirectory ( $dir ) <
if (! file_exists ( $dir )) return true ;
if (! is_dir ( $dir ) || is_link ( $dir )) return unlink ( $dir );
foreach ( scandir ( $dir ) as $item ) <
if ( $item == ‘.’ || $item == ‘..’ ) continue;
if (! deleteDirectory ( $dir . «/» . $item )) <
chmod ( $dir . «/» . $item , 0777 );
if (! deleteDirectory ( $dir . «/» . $item )) return false ;
>;
>
return rmdir ( $dir );
>
?>

[EDITOR NOTE: «Credits to erkethan at free dot fr.» — thiago]

Sometimes you would face situations in which rmdir($dirname) would give «permission denied» errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir(‘dirr’); then change the permissions of the folder that contains ‘dirr’.

a simple snipped for removing empty dirs recursive :

function removeEmptyDirs ( $fullPath )
if(! is_dir ( $fullPath )) return;
>

$children = array_diff ( scandir ( $fullPath ), [ ‘.’ , ‘..’ ]);

foreach( $children as $child ) removeEmptyDirs ( $fullPath . $child . DIRECTORY_SEPARATOR );
>

$children = array_diff ( scandir ( $fullPath ), [ ‘.’ , ‘..’ ]);
if(empty( $children )) echo «the $fullPath empty directory has been removed.\n» ;
rmdir ( $fullPath );
>
>
?>

In case you’re trying to rmdir() and you keep getting ‘Permission denied’ errors, make sure you don’t have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().

Concise way to recursively remove a directory:

# recursively remove a directory
function rrmdir ( $dir ) foreach( glob ( $dir . ‘/*’ ) as $file ) if( is_dir ( $file ))
rrmdir ( $file );
else
unlink ( $file );
>
rmdir ( $dir );
>
?>

if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

if( file_exists ( $path . ‘/Thumbs.db’ )) <
unlink ( $path . ‘/Thumbs.db’ );
>
?>

and then

This isn’t my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

function deleteAll ( $directory , $empty = false ) <
if( substr ( $directory ,- 1 ) == «/» ) <
$directory = substr ( $directory , 0 ,- 1 );
>

if(! file_exists ( $directory ) || ! is_dir ( $directory )) <
return false ;
> elseif(! is_readable ( $directory )) <
return false ;
> else <
$directoryHandle = opendir ( $directory );

if( is_dir ( $path )) <
deleteAll ( $path );
> else <
unlink ( $path );
>
>
>

if( $empty == false ) <
if(! rmdir ( $directory )) <
return false ;
>
>

Источник

Оцените статью