3

我这个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 等等...

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

4

3 回答 3

14

你可以这样做:

$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;
于 2013-09-24T03:47:24.797 回答
0
  1. 您上传了一个名为demo.png.
  2. 您尝试上传相同的文件demo.png,但它被重命名为demo2.png.
  3. 当您尝试demo.png第三次上传时,它会demo1.png再次重命名为并替换您在 (2) 中上传的文件。

所以你不会找到demo3.png

于 2016-07-25T07:39:58.867 回答
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);
于 2021-01-21T06:52:27.017 回答