Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Unlink All Files Within A Directory, and then Deleting That Directory

Tags:

php

unlink

rmdir

I there a way I can use RegExp or Wildcard searches to quickly delete all files within a folder, and then remove that folder in PHP, WITHOUT using the "exec" command? My server does not give me authorization to use that command. A simple loop of some kind would suffice.

I need something that would accomplish the logic behind the following statement, but obviously, would be valid:

  $dir = "/home/dir" unlink($dir . "/*"); # "*" being a match for all strings rmdir($dir);  
like image 852
NoodleOfDeath Avatar asked Jun 29 '12 18:06

NoodleOfDeath


People also ask

How can I Delete all files in a directory in PHP?

If you want to delete everything from folder (including subfolders) use this combination of array_map , unlink and glob : array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

How do you remove a directory and all files in it?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

Is there any method to erase all files in the current directory along with its all sub-directories by using only one command?

rm command – removes a directory/folder along with all the files and sub-directories in it.

What is unlink in PHP?

The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure. Syntax: unlink( $filename, $context )


2 Answers

Use glob to find all files matching a pattern.

function recursiveRemoveDirectory($directory) {     foreach(glob("{$directory}/*") as $file)     {         if(is_dir($file)) {              recursiveRemoveDirectory($file);         } else {             unlink($file);         }     }     rmdir($directory); } 
like image 66
Lusitanian Avatar answered Oct 06 '22 00:10

Lusitanian


Use glob() to easily loop through the directory to delete files then you can remove the directory.

foreach (glob($dir."/*.*") as $filename) {     if (is_file($filename)) {         unlink($filename);     } } rmdir($dir); 
like image 34
John Conde Avatar answered Oct 06 '22 01:10

John Conde