Recursively Delete Matching Files via PHP -
i reworked naming convention of images on our website. when uploaded images altered names, ended getting images duplicated, 1 copy old naming convention , 1 new naming convention. images numbered in thousands , didn't want manually delete them all.
so decided needed figure out php script capable of deleting old images site. luckily old images consistently named either ending of f.jpg or s.jpg. had find files endings , delete them. thought straightforward thing, whatever reason several different solutions found listed online didn't work right. ended going old code had posted on stackoverflow different purpose , reworked this. i'm posting code answer problem in case might useful else.
below solution finding files matching naming convention in selected folder , sub-folders , deleting them. make work situation. you'll want place above directory want delete, , you'll specify specific folder replacing part have ./media/catalog/
. you'll want replace criteria have selected, namely (substr($path, -5)=='f.jpg' || substr($path, -5)=='s.jpg')
. note 5 in preceding code refers how many letters being matched in criteria. if wanted match ".jpg" replace 5 4.
as always, when working code can effect lot of files, sure make backup in case code doesn't work way expect will.
<?php #stick clearoldjpg.php above folder want delete function clearoldjpg(){ $iterator = new recursiveiteratoriterator(new recursivedirectoryiterator("./media/catalog/")); $files = iterator_to_array($iterator, true); // iterate on directory foreach ($files $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 code list files being deleted , tell how long took run.
Comments
Post a Comment