PHP Rename File name if Exists Append Number to End

user2201765 picture user2201765 · Apr 21, 2013 · Viewed 29.6k times · Source

I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!

PHP

$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{           
    $actual_name = (string)$actual_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
}

Answer

Jason picture Jason · Apr 21, 2013

Here's a minor modification that I think should do what you want:

$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);

$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{           
    $actual_name = (string)$original_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
}