重命名文件(如果已存在)-PHP Upload System [英] Rename a file if already exists - php upload system

查看:184
本文介绍了重命名文件(如果已存在)-PHP Upload System的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这是PHP代码:

<?php

// Check for errors
if($_FILES['file_upload']['error'] > 0){
    die('An error ocurred when uploading.');
}

if(!getimagesize($_FILES['file_upload']['tmp_name'])){
    die('Please ensure you are uploading an image.');
}

// Check filesize
if($_FILES['file_upload']['size'] > 500000){
    die('File uploaded exceeds maximum upload size.');
}

// Check if the file exists
if(file_exists('upload/' . $_FILES['file_upload']['name'])){
    die('File with that name already exists.');
}

// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], 'upload/' . $_FILES['file_upload']['name'])){
    die('Error uploading file - check destination is writeable.');
}

die('File uploaded successfully.');

?>

我需要像对待现有文件一样对Windows进行处理-我的意思是如果文件存在,我希望将其更改为文件名,后跟数字1.

and I need to act like a "windows" kind of treatment for existing files - I mean the if the file exists, i want it to be changed to the name of the file with the number 1 after it.

例如:myfile.jpg已经存在,因此,如果再次上传它将是myfile1.jpg,如果myfile1.jpg存在,它将是myfile11.jpg,依此类推...

for example: myfile.jpg is already exists, so if you'll upload it again it will be myfile1.jpg, and if myfile1.jpg exists, it will be myfile11.jpg and so on...

我该怎么做?我尝试了一些循环,但不幸的是没有成功.

how can i do it? i tried some loops but unfortunately without success.

推荐答案

您可以执行以下操作:

$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);

// add a suffix of '1' to the file name until it no longer conflicts
while(file_exists($name . '.' . $extension)) {
    $name .= '1';
}

$basename = $name . '.' . $extension;

为避免名字太长,可能会比较聪明地添加一个数字,例如file1.jpgfile2.jpg等:

To avoid very long names, it would probably be neater to append a number, e.g. file1.jpg, file2.jpg etc:

$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);

$increment = ''; //start with no suffix

while(file_exists($name . $increment . '.' . $extension)) {
    $increment++;
}

$basename = $name . $increment . '.' . $extension;

这篇关于重命名文件(如果已存在)-PHP Upload System的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆