I am trying to figure out a way to clean my temporary storage space using php. I know I can setup cron jobs but, is there a way to do it from php itself?
I use a temporary storage folder for storing generated pdf files for user to download. I have managed to force an expiry on the file so it will no longer be available publically to access after 3 minutes. Now the issue. Although the file is not accessible publically, It is still stored in my server. I have coded something like this to clean up the storage.
/** from the main thread */
if (rand(1, 100) <= 5) {
Reports::clean();
}
/** the clean function */
public static function clean()
{
$path = static::getStoragePath();
if($dir_handle = opendir($path)) {
while (($fileName = readdir($dir_handle)) !== false) {
$file = $path . '/' . $fileName;
if (!is_file($file))
continue;
// If file is older that 3 minutes delete it
if (time() - filemtime($file) > static::$expires) {
unlink($file);
}
}
closedir($dir_handle);
}
}
so this will clean up the storage randomly. Mostly this is fine. but the issue is when the storage clean up starts this slow down that request like turtle.
So I thought of creating a cronjob. But is there a right way to do this from php itself?
Note: I am using slim-4, also don't have much expertise on setting up cronjobs. So any resource will also be helpful