Php delete all files in folders

Deleting all files from a folder using PHP?

For example I had a folder called `Temp’ and I wanted to delete or flush all files from this folder using PHP. Could I do this?

It’s a good thing this question was answered down below before it was marked as duplicate. The answers below are way better than the linked answered question. Plus the question is different, this question asks to empty a directory, not delete.

Yeah, this is a different question that drew different answers. It should not be marked as a duplicate.

18 Answers 18

$files = glob('path/to/temp/*'); // get all file names foreach($files as $file) < // iterate files if(is_file($file)) < unlink($file); // delete file >> 

If you want to remove ‘hidden’ files like .htaccess, you have to use

$files = glob('path/to/temp/*', GLOB_BRACE); 

Although it’s obvious, I’d mention that, for example, ‘path/to/temp/*.txt’ will remove only txt files and so on.

Does this also works for relative paths? So let’s say the full path is «/var/www/html/folder_and_files_to_delete/» And the delete script is placed in «/var/www/html/delete_folders_and_files.php». Can I just take «folder_and_files_to_delete» as path?

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/*"))); 

This can also handle empty directories (thanks for the tip, @mojuba!)

Best answer, thanks. To avoid notices I’d also do glob(«. «) ?: [] (PHP 5.4+) because for an empty directory glob() returns false .

It deletes all files in the current folder, but it returns a warning for subfolders and doesn’t delete them.

@Ewout : Even if we combine Stichoza’s and Moujuba’s answer as your give returns the same warning for subfolders and it doesn’t delete them

Here is a more modern approach using the Standard PHP Library (SPL).

$dir = "path/to/directory"; if(file_exists($dir))< $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); foreach ( $ri as $file ) < $file->isDir() ? rmdir($file) : unlink($file); > > 

This works nicely, when you have no SSH access and FTP takes literally hours to recursive delete lots of files and folders. with those lines I deleted 35000 files in less than 3 seconds!

For PHP 7.1 users : $file->getRealPath() must be used instead of $file. Otherwise, PHP will give you an error saying that unlink requires a path, not an instance of SplFileInfo.

This solution is crashing server — localhost and also online server. Not good solution for me. Thanks.

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) < if(!$fileInfo->isDot()) < unlink($fileInfo->getPathname()); > > 

it should be unlink(‘/path/to/directory/’.$fileInfo->getFilename()); since unlink takes in the path. Good answer though.

You could even do unlink($fileInfo->getPathname()); which would give you the full path to the file. php.net/manual/en/directoryiterator.getpathname.php

Doesn’t ‘DirectoryIterator’ also iterate over subdirectories? If so ‘unlink’ would generate a warning in such cases. Shouldn’t the body of the loop look more like in Yamiko’s answer instead and check each entry if it’s a file before calling ‘unlink’?

/** * Delete a file or recursively delete a directory * * @param string $str Path to file or directory */ function recursiveDelete($str) < if (is_file($str)) < return @unlink($str); >elseif (is_dir($str)) < $scan = glob(rtrim($str,'/').'/*'); foreach($scan as $index=>$path) < recursiveDelete($path); >return @rmdir($str); > > 
$dir = 'your/directory/'; foreach(glob($dir.'*.*') as $v)

Assuming you have a folder with A LOT of files reading them all and then deleting in two steps is not that performing. I believe the most performing way to delete files is to just use a system command.

For example on linux I use :

exec('rm -f '. $absolutePathToFolder .'*'); 

Or this if you want recursive deletion without the need to write a recursive function

exec('rm -f -r '. $absolutePathToFolder .'*'); 

the same exact commands exists for any OS supported by PHP. Keep in mind this is a PERFORMING way of deleting files. $absolutePathToFolder MUST be checked and secured before running this code and permissions must be granted.

@LawrenceCherone I hope noone runs php with root permissions nowadays. Being serious, I expect the input to be «secure», as all of the above functions.

The most voted solutions don’t work in dev environments where www or www-data is not the owner. It’s up to the server admin to ensure the proper rights of the folder are set. exec is an invaluable tool for getting things done, and with great power, etc. stackoverflow.com/a/2765171/418974

The simple and best way to delete all files from a folder in PHP

$files = glob('my_folder/*'); //get all file names foreach($files as $file) < if(is_file($file)) unlink($file); //delete file >

unlinkr function recursively deletes all the folders and files in given path by making sure it doesn’t delete the script itself.

function unlinkr($dir, $pattern = "*") < // find all files and folders matching pattern $files = glob($dir . "/$pattern"); //interate thorugh the files and folders foreach($files as $file)< //if it is a directory then re-call unlinkr function to delete files inside this directory if (is_dir($file) and !in_array($file, array('..', '.'))) < echo "

opening directory $file

"; unlinkr($file, $pattern); //remove the directory itself echo "

deleting directory $file

"; rmdir($file); > else if(is_file($file) and ($file != __FILE__)) < // make sure you don't delete the current script echo "

deleting file $file

"; unlink($file); > > >

if you want to delete all files and folders where you place this script then call it as following

//get current working directory $dir = getcwd(); unlinkr($dir); 

if you want to just delete just php files then call it as following

you can use any other path to delete the files as well

This will delete all files in home/user/temp directory.

Источник

Php delete all files in folders

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in 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.

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.

Источник

Delete directory with files in it?

I wonder, what’s the easiest way to delete a directory with all its files in it? I’m using rmdir(PATH . ‘/’ . $value); to delete a folder, however, if there are files inside of it, I simply can’t delete it.

Just want to note. I created multiple files and if during the process get some error, then need to delete the previously created files. When created files, forgot to use fclose($create_file); and when delete, got Warning: unlink(created_file.xml): Permission denied in. . So to avoid such errors must close created files.

34 Answers 34

There are at least two options available nowadays.

    Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:

public static function deleteDir($dirPath) < if (! is_dir($dirPath)) < throw new InvalidArgumentException("$dirPath must be a directory"); >if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') < $dirPath .= '/'; >$files = glob($dirPath . '*', GLOB_MARK); foreach ($files as $file) < if (is_dir($file)) < self::deleteDir($file); >else < unlink($file); >> rmdir($dirPath); > 
$dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree'; $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) < if ($file->isDir())< rmdir($file->getRealPath()); > else < unlink($file->getRealPath()); > > rmdir($dir); 

Источник

Читайте также:  Как объединить переменные php
Оцените статью