PHP Rename File name if Exists Append Number to End

前端 未结 3 1784
逝去的感伤
逝去的感伤 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 00:15

    Inspired from @Jason answer, i created a function which i deemed shorter and more readable filename format.

    function newName($path, $filename) {
        $res = "$path/$filename";
        if (!file_exists($res)) return $res;
        $fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
    
        $i = 1;
        while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
        return "$path/$fnameNoExt ($i).$ext";
    }
    

提交回复
热议问题