In this article, Bien Thuy will guide you “Automatically deleting cache folder using PHP & Cron Jobs”. PHP file will help you delete a folder and recreate it automatically every hours, daily or every week, it depend on your setting on Cron Jobs.

Let start with PHP file:
Create a php file call auto_delete.php and upload it to your host, anywhere you want to stored it. Of course, it much be outside of folder you want to delete.
Content of that file, copy and paste code below and save: Change “/home/username/public_html/cache” to absolute path to the folder you want to delete.

<?PHP
/*
Package Name: Auto delete cache folder using php and Cron Jobs
Version: 1.0.0
Author: Bien Thuy
Author URI: https://bienthuy.com
License: GNU General Public License
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Copyright: (c) 2015 Bien Thuy - BienThuy.Com.
*/
$lbt = "/home/username/public_html/cache";
$ltllbt = new RecursiveDirectoryIterator($lbt, RecursiveDirectoryIterator::SKIP_DOTS);
$lnllbts = new RecursiveIteratorIterator($ltllbt, RecursiveIteratorIterator::CHILD_FIRST);
foreach($lnllbts as $lnllbt) {
    if ($lnllbt->isDir()){
        rmdir($lnllbt->getRealPath());
    } else {
        unlink($lnllbt->getRealPath());
    }
}
rmdir($lbt);
mkdir($lbt);
echo "<center><h1>All done. $lbt has been deleted and recreated.</h1></center>";
?>

Now, go to your hosting cpanel, look for Cron Jobs, and add new Cron Jobs:

Common Settings: choose the best match your point. If you have dynamic cache and more cached files, you choose “Twice a day” or “Once a day”. Otherwise, you should choose “Once a week”.
Command: Input this line:

/opt/php/bin/php /home/username/public_html/cache/auto_delete.php

Remember to change: /home/username/public_html/cache/auto_delete.php  to your absolute path of your php file above. Ask your hosting provider for path to php script. In my case, php script is locate at: /opt/php/bin/php

Automatically deleting cache folder using PHP & Cron Jobs
Automatically deleting cache folder using PHP & Cron Jobs

Finally, save it by enter Add New Cron Job. Now, you are done. You can check it by view it on your browser, enter url to auto_delete file on address bar and see if it show you that ” All done. /home/username/public_html/cache has been deleted and recreated. ”
If it show that line, you are successful  scheduled for Automatically deleting cache folder.

4.8/5 - (2419 bình chọn)

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *