Search code examples
phpjoomlacroncron-task

Cron Job - delete zip files from a specific directory


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?


Solution

  • 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)