PHP Rename File name if Exists Append Number to End

前端 未结 3 1787
逝去的感伤
逝去的感伤 2021-01-30 23:40

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

3条回答
  •  佛祖请我去吃肉
    2021-01-31 00:13

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

提交回复
热议问题