Octo Tawatpong
Octo Tawatpong

Reputation: 19

Rename Many Files in a Folder - PHP

I have 2500 images in a Folder, which has NAME word in all the images. For examples

Peter Wang B5357550.jpg
Sander Mackiney B5355624.jpg

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

B5357550.jpg
B5355624.jpg

So remove NAME and SURNAME from filename, is it possible in PHP to do bulk renaming ? (All student IDs are in format of Bxxxxxxx)

Upvotes: 0

Views: 2822

Answers (2)

Kārlis Millers
Kārlis Millers

Reputation: 674

Quick, simple solution:

$dir = $_SERVER['DOCUMENT_ROOT'].'/your-folder-to-files';
$files = scandir($dir);
unset($files[0],$files[1]);
foreach ($files as $oldname){
    $newname = substr($oldname, -12);
    rename ($dir.'/'.$oldname, $dir.'/'.$newname);
}

N.B.: You may need to change the server path to something similar to:

$dir = "/home/users/you/folder_files/";

or

$dir = "folder_files/";
  • If $_SERVER['DOCUMENT_ROOT'] does not work for you.

Upvotes: 2

Zach Bloomquist
Zach Bloomquist

Reputation: 5871

If they're all in that format, it would be simple to fix, yes. Run glob to get all the .jpg files into an array, then simply explode the filename on spaces, use a foreach loop on that array, use end to get the last section, and rename the file to that string.

Upvotes: -1

Related Questions