Search code examples
phpfile-uploadserver

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


I got a task where I need to upload the same file name with numbers. For example if I upload file1 with the title "cv.pdf" then second file should be named as "cv.pdf(1)",the next one should be "cv.pdf(2)" and so on.

I have tried many ways but still not working out. Can some please help me out to meet the desired objective. This is my

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);
?>
    

Solution

  • I think glob function is your savior here.

    Istead of:

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

    You should use:

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

    And last, but not least, you should change the final name of the file:

    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