Delete all files in a directory with PHP.

  • RedBMedia
  • Proficient
  • Proficient
  • User avatar
  • Posts: 315

Post 3+ Months Ago

I am trying to write a script that deletes all the files for a directory called "cache". My plan is to get this working and then setup a cronjob to run every hour so my server doesn't get filled up with wasted crap. So, anyways, heres what I have so far, and for some reason its not working. No errors, its just not working.

PHP Code: [ Select ]
if ($handle = opendir('cache')) {
   while (false !== ($file = readdir($handle))) {
  1. if ($handle = opendir('cache')) {
  2.    while (false !== ($file = readdir($handle))) {
  3.       unlink($file);
  4.    }
  5. closedir($handle);
  6. }

Any ideas?
  • ScienceOfSpock
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1893
  • Loc: Las Vegas

Post 3+ Months Ago

There are two blatant issues with your script that I can see.

First, $file will only contain the filename, not the path.
In your case, you are reading the cache/ directory relative to the current script, but you are trying to delete $file, rather than cache/$file.

PHP Code: [ Select ]

PHP Code: [ Select ]

And that should get it deleting files properly.

Second, You are not excluding the '.' or '..' directory references (which WILL come up in the file list, regardless of operating system.)
This will usually throw permission warnings, but won't stop the script from running.
You should add in an if statement that excludes those references:
PHP Code: [ Select ]
if ( $file != '.' && $file != '..' )
   unlink ( 'cache/'.$file );
  1. if ( $file != '.' && $file != '..' )
  2. {
  3.    unlink ( 'cache/'.$file );
  4. }

If you are still having problems after fixing these things, then you have a permission issue. PHP can only delete files that are owned by the same process that it runs under (the apache user, in many cases). In the case of shared servers, the permission issue gets much more complicated.


Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 25 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum

© 1998-2017. Ozzu® is a registered trademark of Unmelted, LLC.