Search code examples
phpfile-uploaduploadrenamefile-exists

PHP Rename File name if Exists Append Number to End


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++;
}

Solution

  • 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++;
    }