To delete all files older than 2 days in PHP and set up a cron job to run the script automatically, you can use the following steps:
Â
- Create a new PHP file that contains the code to delete the files, as described in the previous answer. For example, you can create a file called
delete_old_files.phpand add the following code:
Â
$directory = '/path/to/directory/';
// Get all files in the directory
$files = glob($directory . '*');
// Iterate over the files
foreach ($files as $file) {
// Check if the file was last modified more than 2 days ago
if (filemtime($file) < time() - 2 * 24 * 60 * 60) {
// Delete the file
unlink($file);
}
}
Â
Make sure to replace /path/to/directory/ it with the actual path to the directory in which you want to delete files.
Â
- Set up a cron job to run the script automatically. You can do this by logging in to your server and running the following command:
Â
crontab -e
Â
This will open the crontab file in an editor. Add the following line at the end of the file:
Â
0 0 * * * php /path/to/delete_old_files.php
Â
This will run the delete_old_files.php the script at midnight every day.
Â
Make sure to replace /path/to/delete_old_files.php it with the actual path to the PHP file that you created in step 1.
- Save and exit the crontab file.
Â
Â
That's it! The script will now run automatically at the specified time and delete all files in the specified directory that are older than 2 days.
Jayanta DK
Community Forum
We’re currently working on improving our forum experience.