i would like to create a PHP script that delete files from multiple folders/paths. I managed something but I would like to adapt this code for more specific folders.
This is the code:
<?php function deleteOlderFiles($path,$days) { if ($handle = opendir($path)) { while (false !== ($file = readdir($handle))) { $filelastmodified = filemtime($path . $file); if((time() - $filelastmodified) > $days*24*3600) { if(is_file($path . $file)) { unlink($path . $file); } } } closedir($handle); } } $path = 'C:/Users/Legion/AppData/Local/Temp'; $days = 7; deleteOlderFiles($path,$days); ?>
I would like to make something like to add more paths and this function to run for every path. I tried to add multiple path locations but it didn’t work because it always takes the last $ path variable. For exemple:
$path = 'C:/Users/Legion/AppData/Local/Temp'; $path = 'C:/Users/Legion/AppData/Local/Temp/bla'; $path = 'C:/Users/Legion/AppData/Local/Temp/blabla'; $path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba'; $days = 7; deleteOlderFiles($path,$days);
Thank you for you help!
Advertisement
Answer
The simple solution, call the function after setting the parameter not after setting all the possible parameters into a scalar variable.
$days = 7; $path = 'C:/Users/Legion/AppData/Local/Temp'; deleteOlderFiles($path,$days); $path = 'C:/Users/Legion/AppData/Local/Temp/bla'; deleteOlderFiles($path,$days); $path = 'C:/Users/Legion/AppData/Local/Temp/blabla'; deleteOlderFiles($path,$days); $path = 'C:/Users/Legion/AppData/Local/Temp/blalbalba'; deleteOlderFiles($path,$days);
Alternatively, place the directories in an array and then call the funtion from within a foreach loop.
$paths = []; $paths[] = 'C:/Users/Legion/AppData/Local/Temp'; $paths[] = 'C:/Users/Legion/AppData/Local/Temp/bla'; $paths[] = 'C:/Users/Legion/AppData/Local/Temp/blabla'; $paths[] = 'C:/Users/Legion/AppData/Local/Temp/blalbalba'; $days = 7; foreach ( $paths as $path){ deleteOlderFiles($path,$days); }