Question

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?

Was it helpful?

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)

OTHER TIPS

you are passing only file names here mate

unlink('/home/MYUSER/public_html/MYSITE/modules/mod_module_gen/package/'.$file);

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top