【问题标题】:Rename a file if already exists - php upload system重命名文件,如果已经存在 - php上传系统
【发布时间】:2013-09-29 03:10:50
【问题描述】:

我这个 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 以此类推……

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

【问题讨论】:

标签: php file upload exists


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 我该怎么做? :)
  • 我添加了一个例子。
  • 乔治先生,我试过你的第二个代码,因为 $increment++ 不起作用。你能帮我吗
  • @Hybreeder 请详细说明“不工作” - 有什么错误吗?
  • 例如我上传的第一个文件名是 demo.png,第二次我上传了相同的文件名 demo.png 并由 demo1.png 重命名。这没有问题,但是当我第三次上传相同的文件时然后什么都没有发生。我没有 demo2.png....请帮助我。
【解决方案2】:
  1. 您上传了一个名为 demo.png 的文件。
  2. 您尝试上传同一文件 demo.png,但它已重命名为 demo2.png
  3. 当您第三次尝试上传 demo.png 时,它会再次重命名为 demo1.png 并替换您在 (2) 中上传的文件。

所以你不会找到demo3.png

【讨论】:

    【解决方案3】:

    对于用户 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);
    

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 2015-06-14
      • 2014-04-02
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2012-04-02
      相关资源
      最近更新 更多