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

时间:2013-09-24 03:30:27

标签: php file upload exists

我这个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的文件名。

例如:myfile.jpg已经存在,所以如果你再次上传它将是myfile1.jpg,如果myfile1.jpg存在,它将是myfile11.jpg等等......

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

3 个答案:

答案 0 :(得分:13)

你可以这样做:

$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等:

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

答案 1 :(得分:0)

  1. 您上传了一个名为demo2.png
  2. 的文件
  3. 您尝试上传相同的文件demo.png,并将其重命名为demo1.png
  4. 当您尝试第三次上传demo3.png时,会再次将其重命名为{{1}}并替换您在(2)中上传的文件。
  5. 因此您无法找到{{1}}

答案 2 :(得分:0)

对于用户6930268; 我认为你的代码应该是:

$name = pathinfo($_FILES['file_upload']['name'], PATHINFO_FILENAME);
$extension = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
$dirname = pathinfo($_FILES['file_upload']['name'], PATHINFO_DIRNAME);
$dirname = $dirname. "/";
$increment = ''; //start with no suffix

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

$basename = $name . $increment . '.' . $extension;
$resultFilePath = $dirname . $name . $increment . '.' . $extension);