本文介绍了php检查文件名是否存在,重命名该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查文件名是否存在,重命名文件?
How do I check if file name exists, rename the file?
例如,如果文件存在,我上传图像1086_002.jpg
,将文件重命名为1086_0021.jpg
并保存,如果1086_0021.jpg
存在,则重命名1086_00211.jpg
并保存,如果1086_00211.jpg
存在,则重命名1086_002111.jpg
并保存...
for example, I upload a image 1086_002.jpg
if the file exists, rename the file as 1086_0021.jpg
and save, if 1086_0021.jpg
is exist, rename 1086_00211.jpg
and save , if 1086_00211.jpg
is exist, rename 1086_002111.jpg
and save...
这是我的代码,仅当1086_002.jpg
存在时才能执行,将文件重命名为1086_0021.jpg
,也许应该执行一次foreach,但是如何?
Here is my code, it only can do if 1086_002.jpg
exist, rename the file as 1086_0021.jpg
, maybe should do a foreach, but how?
//$fullpath = 'images/1086_002.jpg';
if(file_exists($fullpath)) {
$newpieces = explode(".", $fullpath);
$frontpath = str_replace('.'.end($newpieces),'',$fullpath);
$newpath = $frontpath.'1.'.end($newpieces);
}
file_put_contents($newpath, file_get_contents($_POST['upload']));
推荐答案
尝试类似的方法:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
这篇关于php检查文件名是否存在,重命名该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!