开发者

Avoiding duplicate in file saving by php

For making the file name unique, I use this code to add an unique id at the end of filename:

if (!file_exists("data/$filename")) {$savingfile=$filename;} else {$savingfile="$filename-2";}
开发者_JAVA技巧

This method perfectly works, but what is the simple way to continue this loop if "$filename-2" exists save it as "$savefile-3" and so forth (to find an non-exist file name)?


$savingfile = $filename;
$i = 0;
while(file_exists($savingfile)) {
    $savingfile = $filename . '-' . ++$i;
}


You can try to use a counter and compute the filename and check if it exists.

Another approach would be to save somewhere the last value and when you need to create another file just increment it, use it and then save it again.


Personally, I'd just use tmpnam, which is a built-in PHP function to create a file with a unique name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜