如何在 PHP 中上传自动递增的相同文件名?

How to upload same file name with auto increment in PHP?

我接到一个任务,我需要上传带有数字的相同文件名。例如,如果我上传文件 1 的标题为“cv.pdf”,那么第二个文件应命名为“cv.pdf(1)”,下一个文件应命名为“cv.pdf(2)”,并且等等。

试了很多方法还是不行。可以请一些人帮助我满足期望 objective。这是我的

upload.php

<?php 
$json = array();
if(!empty($_FILES['upl_file'])){ 
    $dir = "./uploads/"; 
    $allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx'); 
    $fileName = basename($_FILES['upl_file']['name']); 
    $filePath = $dir.$fileName; 

$actual_name = pathinfo($filePath,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filePath, PATHINFO_EXTENSION);

$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{           
    $actual_name = (string)$original_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
} 
    if(in_array($extension, $allowTypes)){ 
        // Upload file to the server 
        if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath)){ 
            $json = 'success'; 
        } else {
            $json = 'failed';
        }
    } 
}
header('Content-Type: application/json');
echo json_encode($json);
?>
    

我认为 glob 函数是你的救星。

我代替:

$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{           
    $actual_name = (string)$original_name.$i;
    $name = $actual_name.".".$extension;
    $i++;
} 

你应该使用:

$count = count(glob("./uploads/".$actual_name."*.".$extension)); 
  //Check the * after the name

//EDIT: Before add the count, check if its not zero(0)

$actual_name = "{$name}".( $count > 0 ? "({$count})" : "").".{$extension}";

最后但同样重要的是,您应该更改文件的最终名称:

if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath)) 
  //filePath has the old name

if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $dir.$actual_name))
  //newPath with count in the name