Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Example Interest Rates: Home Loan Variable: 2.54% (2.74%*) • Home Loan Fixed: 3.74% (3.8%*) • Fixed: 2.48% (2.94%*) • Variable: 2.54% (2.74%*) • Investment IO: 2.3% (3.76%*) • Investment PI: 2.04% (3.8%*)

Recursively Delete a Directory and all its Contents with PHP

Recursively Delete a Directory and all its Contents with PHP

PHP's unlink function will delete a single file and rmdir will delete an empty directory. However, to delete a directory and all contents below it, we require a recursive solution that will hunt down each file through each directory and delete them individually. The first PHP function on this page is one that I use regularly enough; it'll delete the entire contents of a directory and return either true or false on completion.

What does recursive mean? Recursion, or a recursive function in programming, relates to a procedure that can repeat itself indefinitely (or repeatedly). In our function, we initially scan the directory to be deleted and create an array of the directory root. We iterate over the created array and either apply the same function to a directory or delete a file. The Boolean result is returned on the basis of the target directory being deleted (since it won't delete if there's any files left).

The PHP Function

1
<?php 
2
/*
3
 Recursively Delete a Directory and all its Contents with PHP
4
 http://www.beliefmedia.com/php-delete-directory-contents
5
*/
6
 
7
function beliefmedia_delete_directory($dir) {
8
 if (is_dir($dir)) {
9
  $objects = scandir($dir);
10
   foreach ($objects as $object) {
11
     if ($object != '.' && $object != '..') {
12
      (filetype($dir . '/' . $object) == 'dir') ? beliefmedia_delete_directory($dir . '/' . $object) : unlink($dir . '/' . $object);
13
     }
14
   }
15
  reset($objects);
16
  return rmdir($dir) ? true : false;
17
 }
18
}
19
 
20
/* Usage */
21
$dir = '/some/directory/todelete/';
22
echo beliefmedia_delete_directory($dir) ? 'Success' : 'Failed';

The same modified function can be used to print the contents of an entire directory (with or without the directory structure). Be careful you don't delete anything you're not meant to.

How About GLOB?

I also use a GLOB related function myself for various tasks but, in the case of recursive deletions, it doesn't detect hidden files (so it's unacceptable for full tree deletions). A scandir option seems to work better most of the time.

PHP's GLOB is a really funky function for a range of other tasks. To delete files with a specific file extension within a specific directory, you might consider using something to the function below. Given a directory and a string of file types, it'll delete all the files that match a particular pattern. You could of course have an array of extensions to delete and build that into the recursive function above... but that would defeat the purpose of providing a GLOB example!

1
<?php 
2
/*
3
 Delete Files of a Specific Type from a Directory with PHP and GLOB
4
 http://www.beliefmedia.com/php-delete-directory-contents
5
*/
6
 
7
function beliefmedia_delete_files($dir, $type = '') {
8
 /* Correct for spaces and period in type args */
9
 $extensions = preg_replace('/\s+/', ' ', $type);
10
 $extensions = str_replace('.', '', $extensions);
11
 
12
 /* Make sure we have a trailing slash */
13
 $dir = (substr($dir, -1) == '/' ? '' : '/');
14
 
15
  /* Create glob string */
16
  $extensions = explode(',', $type);
17
   foreach($extensions as $ext) {
18
    $glob .= '.' . strtolower($ext) . ',';
19
    $glob .= '.' . strtoupper($ext) . ',';
20
   }
21
 
22
  /* GLOB_BRACE string */
23
  $glob = '*{' . rtrim($glob, ',') . '}';
24
 
25
  /* Delete files */
26
  foreach ( (glob($dir . $glob, GLOB_BRACE)) as $filename) {
27
   $return .= $filename . ' Size: ' . filesize($filename) . ' deleted.<br>';
28
   unlink($filename);
29
  }
30
 return $return;
31
}
32
 
33
$dir = '/some/directory/todelete/';
34
echo beliefmedia_delete_files($dir, $type = 'txt,php,png');

The function provides a couple of input corrections; we'll remove white spaces from the type string (tends to mess up the search), and we'll add a trailing slash to the dir. The latter might be of use in our first example. Since GLOB is cAsE-SenSitiVe we'll also add the string of upper-case extensions to our search (after first forcing lower case extensions).

Download


Title: Recursively Delete a Directory and all its Contents with PHP
Description: Recursively Delete a Directory and all its Contents with PHP.
  Download • Version 0.2, 910.0B, zip, Category: PHP Code & Snippets

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Washington)

  Want to have a chat?
 

RELATED READING

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment