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))) {
      unlink($file);
   }
closedir($handle);
}
 
  1. if ($handle = opendir('cache')) {
  2.    while (false !== ($file = readdir($handle))) {
  3.       unlink($file);
  4.    }
  5. closedir($handle);
  6. }
  7.  


Any ideas?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • ScienceOfSpock
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1892
  • 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.

Change:
PHP Code: [ Select ]
unlink($file);

to:
PHP Code: [ Select ]
unlink('cache/'.$file);


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.

SoS

Post Information

  • Total Posts in this topic: 2 posts
  • Users browsing this forum: No registered users and 74 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
 
cron
 

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