You may have situations where you want to delete files older than X number of days, but deleting them manually by checking date and time is not possible, and you might have completely avoided deleting the files which is no longer necessary resulting in growing heap of unwanted files in your web-server. Well I was in similar situation, before I became familiar with PHP, but now I always say – know a bit of PHP and it will make your life easier.

delete files in php

Well here we go, the PHP script that deletes the files that is X number of days old. First script, then a bit of explanation.

<? $days = 1; $dir = dirname ( __FILE__ ); $nofiles = 0; if ($handle = opendir($dir)) { while (( $file = readdir($handle)) !== false ) { if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) { continue; } if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) { $nofiles++; unlink($dir.'/'.$file); } } closedir($handle); echo "Total files deleted: $nofiles \n"; } ?>

Now paste this code and save it as a php file, upload it to the folder from where you want to delete the files. You can see at the beginning of this php code

$days = 1;

that sets the number of days, for example if you set it to 2 then files older than 2 days will be deleted. Basically this is what happens when you run the script, gets the current directory and reads the file entries, skips ‘.’ for current directory and further checks if there are any other directories,

if ( $file == '.' || $file == '..' || is_dir($dir.'/'.$file) ) { continue; }

if the file entry is not a directory then it fetches the file modified time (last modified time) and compares, if it is number of days old

if ((time() - filemtime($dir.'/'.$file)) > ($days *86400)) { $nofiles++; unlink($dir.'/'.$file); }

if the condition becomes true then it deletes the file with the help of unlink( ) php function. Finally closes the directory and exits. I have also added a counter to count the number of files being deleted, which will be displayed at the end of deletion process. So place the php file in the directory that needs the file deletion and execute it.

Delete files older than x days in php
Tagged on:                 


3D modeler and Web designer. Founder of Techlister. Love to build sites using Wordpress and Joomla. Interested in Astronomy.

Leave a Reply

Your email address will not be published. Required fields are marked *