重命名文件,如果已经存在 - php上传系统

2022-01-09 00:00:00 file upload php exists

我这个 PHP 代码:

I this PHP code:

<?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;

相关文章