Just Start Typing Text and Press Enter

Menu
Close
Jan 14, 2019

How to Delete Files and Folders in a Directory using PHP

0 Comment | By

This entry explains how to delete files and folders in a directory using PHP. First off in the code below I utilized in a cron utilizing a plugin called WP Crontrol. (not necessary) This allowed me to on the 12th hour of everyday to delete all files in this directory that were uploaded by myself. This can be very handy if you simply want to provide a friend or family member a picture, document, or audio file and then simply link them to it:

E.g. https://davidpolanco.com/downloads/stuff.txt

Once this file is uploaded I can then provide it to them by simply giving them a link. Now by security through obscurity (options index off) they could get access to the stuff.txt file as shown below. The reason why I setup a cron using the PHP code was to ensure that nothing got left behind. It kinda works like a clean up script that will run regardless if I personally delete the files in the directory or not.

I utilize an APP on my laptop that allows me to securely upload a files to my website. The nice thing about this is that the server that is being utilized in this case has plenty of disk and bandwidth that can sustain this traffic / download. However, what I did not want is for this directory to become oversaturated in size and for these files to live on forever. This is the reason I wanted a cron to run against it.


Here is the PHP code:

<?php
define('PATH', '/var/www/downloads/');

function destroy($dir) {
    $mydir = opendir(r);
    while(false !== ($file = readdir($mydir))) {
        if($file != "." && $file != "..") {
            chmod($dir.$file, 0775);
            if(is_dir($dir.$file)) {
                chdir('.');
                destroy($dir.$file.'/');
                rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
            }
            else
                unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
        }
    }
    closedir($mydir);
}
destroy(PATH);
echo 'all done.';
?>

So there you go. This small little php script can be very handy and does exactly what it says/does. In the code I have specified the path, set a permission set to 775 and in any file, or directory in this path will be deleted. You will also get a message if the script could not delete the folder, so be sure to utilize proper permission sets based on your user:group


I know many of you may use it for the wrong reasons but remember, karma.

Leave A Comment

DON'T MISS ANY UPDATES