How to increment filename in php to prevent duplicates

前端 未结 4 1617
忘了有多久
忘了有多久 2020-12-10 17:02

In many situations, we need to make the filename different on the server when creating them to prevent duplication. And the most common answer to that seems to be, append th

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 17:41

    Here is a short code snippet that demonstrates how you might start solving this problem.

    // handle filename collision:
    if(file_exists($newFile)) {
        // store extension and file name
        $extension = pathinfo($newFile,PATHINFO_EXTENSION);
        $filename = pathinfo($newFile, PATHINFO_FILENAME);
    
        // Start at dup 1, and keep iterating until we find open dup number
        $duplicateCounter = 1;
        // build a possible file name and see if it is available
        while(file_exists($iterativeFileName =
                            $newPath ."/". $filename ."_". $duplicateCounter .".". $extension)) {
            $duplicateCounter++;
        }
    
        $newFile = $iterativeFileName;
    }
    
    // If we get here, either we've avoided the if statement altogether, and no new name is necessary..
    // Or we have landed on a new file name that is available for our use.
    // In either case, it is now safe to create a file with the name $newFile
    

提交回复
热议问题