-1

I am trying o delete all zip and rar files from a specific directory. I have set the cron to run a PHP file called cron.php, which is is located in a Joomla module directory. For test purposes, I have set the cron job time to 5 minutes.

I also put a zip file in the directory called test.zip

Command:

php /home/MYUSER/public_html/MYSITE/modules/mod_module_gen/cron.php

PHP: Note: "MYSITE" is the subdomain the site is located

<?php
$dir = "/home/MYUSER/public_html/MYSITE/modules/mod_module_gen/package";
$files = scandir($dir);

foreach ($files as $file) {                   
   if(preg_match("/\.(zip|rar)$/", $file)){
        unlink($file);
   }                    
} 
?>

However every 5 minutes, the error log keeps on throwing the following errors:

PHP Warning:  unlink(test.zip) [<a href='function.unlink'>function.unlink</a>]: No such file or directory in /home/MYUSER/public_html/MYSITE/modules/mod_module_gen/cron.php on line 18

Not sure why this error is occurring as the file does exist. Any ideas?

Lodder
  • 19,758
  • 10
  • 59
  • 100
  • Probably because the file it's trying to unlink doesn't exist (incorrect path), can you try dumping $file – Pez Cuckow Oct 02 '12 at 15:42
  • 1
    This crazy, making a cron job to let php delete files. How about the shell? – JvdBerg Oct 02 '12 at 15:45
  • @JvdBerg - I only chose php cause I thought it might be easier. However if you can point me in the right direction for a shell command only then that would be great. thanks – Lodder Oct 02 '12 at 15:46
  • `rm ` filename can be a mask also. If you fidlle with it it is doable in a single line command. For rm see http://linux.about.com/od/commands/l/blcmdl1_rm.htm – JvdBerg Oct 02 '12 at 15:51
  • something like: `find /home/MYUSER/public_html/MYSITE/modules/mod_module_gen/package/*.zip -name -exec rm -rf () \;` – JvdBerg Oct 02 '12 at 15:56
  • @JvdBerg - thankyou, will also give this a go – Lodder Oct 02 '12 at 15:57
  • 1
    Think the problem is your working directory. unlink($dir . $file); – Trev Oct 02 '12 at 16:00

3 Answers3

7

I believe the problem is that the current directory is treated as where the PHP script is run from.

So the files are in:

/home/MYUSER/public_html/MYSITE/modules/mod_module_gen/package

but the command (once $file is resolved) to delete is:

unlink('test.zip');

As the file is being run from somewhere else (say ~):

PHP is trying to unlink ~/test.zip

Consider doing

unlink($dir.'/'.$file)

Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130
1

you are passing only file names here mate

unlink('/home/MYUSER/public_html/MYSITE/modules/mod_module_gen/package/'.$file);
Surace
  • 701
  • 3
  • 8
1

scandir returns an array of filenames in $dir, but doesn't include the path itself.... you're trying to unset the filename; but unless $dir is your current working directory it is only by happenstance that it might work if there was a file of the same name in your cwd.

Mark Baker
  • 209,507
  • 32
  • 346
  • 385