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

Rename a file if already exists - php upload system(重命名文件,如果已经存在 - php上传系统)
本文介绍了重命名文件,如果已经存在 - php上传系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这个 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;

这篇关于重命名文件,如果已经存在 - php上传系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)