Forum

Efficient PHP Code ...
 
Notifications
Clear all

Efficient PHP Code for Deleting Files: Delete All Files Older than 2 Days the Right Way

 
(@administrator)
Member Admin

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:

 

  1. 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.php and 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.

 

  1. 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.

  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.

Quote
Topic starter Posted : 13/02/2023 7:36 am
Share:
×