Madison Knight
Madison Knight

Reputation: 364

Recursively Delete Matching Files via PHP

I recently reworked the naming convention of some images on our website. When I uploaded the images with altered names, I ended up getting the images duplicated, one copy with the old naming convention and one with the new naming convention. The images numbered in the thousands and so I didn't want to manually delete them all.

So I decided that I needed to figure out a php script that would be capable of deleting the old images from the site. Luckily the old images were consistently named with either an ending of f.jpg or s.jpg. So all I had to do is find all the files with those endings and delete them. I thought it was a fairly straightforward thing, but for whatever reason the several different solutions I found listed online didn't work right. I ended up going back to some old code I had posted on Stackoverflow for a different purpose and reworked it for this. I'm posting that code as the answer to my problem in case it might be useful to anyone else.

Upvotes: 2

Views: 252

Answers (1)

Madison Knight
Madison Knight

Reputation: 364

Below is my solution to finding files matching a certain naming convention in a selected folder and its sub-folders and deleting them. To make it work for your situation. You'll want to place it above the directory that you want to delete, and you'll specify the specific folder by replacing the part where I have ./media/catalog/. You'll also want to replace the criteria I have selected, namely (substr($path, -5)=='f.jpg' || substr($path, -5)=='s.jpg'). Note that the 5 in the preceding code refers to how many letters are being matched in the criteria. If you wanted to simply match ".jpg" you would replace the 5 with a 4.

As always, when working with code that can effect a lot of files, be sure to make a backup in case the code doesn't work the way you expect it will.

<?php #stick ClearOldJpg.php above the folder you want to delete
function ClearOldJpg(){
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./media/catalog/"));
    $files = iterator_to_array($iterator, true);

    // iterate over the directory
    foreach ($files as $path) {
              if( is_file( $path ) && (substr($path, -5)=='f.jpg' || substr($path, -5)=='s.jpg')){ 
                unlink($path);
                echo "$path deleted<br/>";              
              }
    }
}

    $start = (float) array_sum(explode(' ',microtime()));
    echo "*************** Deleting Selected Files ***************<br/>";
    ClearOldJpg( );

    $end = (float) array_sum(explode(' ',microtime()));
    echo "<br/>------------------- Deleting selected files COMPLETED in:". sprintf("%.4f", ($end-$start))." seconds ------------------<br/>";
    ?>

One fun bonus of this code is that it will list the files being deleted and tell how long it took to run.

Upvotes: 2

Related Questions