Skip to content
Advertisement

Bulk Rename Files in a Folder – PHP

I have 1000 images in a Folder, which has SKU# word in all the images. For examples

WV1716BNSKU#.zoom.1.jpg
WV1716BLSKU#.zoom.3.jpg

what i need to do is read all the filenames and rename it to the following

WV1716BN.zoom.1.jpg
WV1716BL.zoom.3.jpg

So remove SKU# from filename, is it possible in PHP to do bulk renaming ?

Advertisement

Answer

Yeah, just open the directory and create a loop to access all images and rename them, like:

<?php

if ($handle = opendir('/path/to/files')) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = str_replace("SKU#","",$fileName);
        rename($fileName, $newName);
    }
    closedir($handle);
}
?>

References:

http://php.net/manual/en/function.rename.php

http://php.net/manual/en/function.readdir.php

http://php.net/manual/en/function.str-replace.php

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement