mattew
mattew

Reputation: 203

Renaming duplicate files in a folder with php

Who can help me to fix the following problem? Here is the issue: in a form POST i made people can upload files. The code below check if in the "uploads" folder there another file with the same name. If so, files are renamed as this example:

hallo.txt
1_hallo.txt
2_hallo.txt

... and so on.

This is the code used:

$OriginalFilename = $FinalFilename = $_FILES['uploaded']['name'];
// rename file if it already exists by prefixing an incrementing number
$FileCounter = 1;
while (file_exists( 'uploads/'.$FinalFilename ))
$FinalFilename = $FileCounter++.'_'.$OriginalFilename;

I would like to rename files in a different way. progressive numbers should be AFTER the file and, of course, before the extention. This is the same example of before but in the way i want:

hallo.txt
hallo_1.txt
hallo_2.txt

... and so on.

How can i modify the code to reach that result? Thank you in advance and sorry for my newbie-style question. I'm really newbie! :)

Mat

Upvotes: 0

Views: 4749

Answers (1)

Paul
Paul

Reputation: 141827

Just change the $FinalFilename:

$FinalFilename = pathinfo($OriginalFilename, PATHINFO_FILENAME) . '_' . $FileCounter++ . '.' . pathinfo($OriginalFilename, PATHINFO_EXTENSION);

Or (better if you have a lot of files with the same name and often iterate more than once):

$filename = pathinfo($OriginalFilename, PATHINFO_FILENAME);
$extension =  pathinfo($OriginalFilename, PATHINFO_EXTENSION);
while (file_exists( 'uploads/'.$FinalFilename ))
    $FinalFilename = $filename . '_' . $FileCounter++ . '.' . $extension;

Upvotes: 8

Related Questions