php生成新文件名,如果文件已存在,则在名字后面跟数字
php生成新文件名,如果文件已存在,则在名字后面跟数字 在上传文件时经常会用到下面的代码片段:```{.php}function file_newname($path, $filename){ if ($pos = strrpos($filename, #39;.#39;)) { $name = substr
在上传文件时经常会用到下面的代码片段:
function file_newname($path, $filename){
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.'/'.$filename;
$newname = $filename;
$counter = 0;
while (file_exists($newpath)) {
$newname = $name .'_'. $counter . $ext;
$newpath = $path.'/'.$newname;
$counter++;
}
return $newname;
}
如下如果myfile.jpg存在则会返回带有_0,_1后缀的文件名:
myfile.jpg
myfile_0.jpg
myfile_1.jpg
- 上一篇:php文件格式和mime-types对应
- 下一篇:PHP阳历转农历实现代码
精彩图集
精彩文章






