Handling Upload Duplicate Filename in PHP Tutorial

In this tutorial, you will learn how to handle the uploaded file with a Duplicate Filename in the uploaded file directory. The tutorial aims to provide IT students and new programmers with a reference for handling uploaded files in PHP with duplicate filenames. I will provide a snippet that achieves the objective of this tutorial. A sample source code zip file that I created for this tutorial is also provided and is free to download.

How to Handle Uploaded Files with Duplicate Filename using PHP?

Uploading Files in PHP using move_uploaded_file() functions without proper handling of the filename may result in overwriting the old uploaded files. Some developer handles the filename of the uploaded file by renaming it into a unique name using their own logic. If you are looking for a way to upload files and preserve the original filename, using while loop and iteration, you can achieve it without saving the filename itself into the database.

Using a while loop and iteration will not totally preserve the exact original filename because we need to add the iterated number with the filename to prevent overwriting the old ones.

Here's an example of Handling Uploaded Files with Duplicate filenames using PHP.

  1. <?php
  2. $dir = "uploads/";
  3. // Get file's path info
  4. $filepath_info = pathinfo($_FILES['upload']['name']);
  5.  
  6. //filename
  7. $filename = $filepath_info['filename'];
  8.  
  9. // File Extension
  10. $extension = $filepath_info['extension'];
  11.  
  12. // Iteration starting Value
  13. $i = 0;
  14.  
  15. while(true){
  16.     // Filename additional text
  17.     $additional_txt = ($i>0) ? " ({$i})" : "";
  18.  
  19.     // Temporary new filename
  20.     $tempname = $filename.$additional_txt.".".$extension;
  21.  
  22.     // Cheching Filename Duplicate
  23.     if(is_file($dir.$tempname)){
  24.         // If has duplicate
  25.         $i++;
  26.     }else{
  27.         // Renew Filename
  28.         $filename = $tempname;
  29.         // break the loop
  30.         break;
  31.     }
  32. }
  33.  
  34.  
  35. // Upload file
  36. $upload = move_uploaded_file($_FILES['upload']['tmp_name'], $dir.$filename);

Using the snippet above, the uploaded file with a duplicate filename on the uploads directory is [original_name] ([iterated_number]).[file_extension].

Example

Here's a sample web application snippet that demonstrates the objectives of this tutorial.

Page Interface

The below snippet contains a combined PHP and HTML Script that outputs a simple page with an upload form and Uploaded files list. Save the snippet as index.php.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Handling Upload w/ Duplicate Filename  | PHP</title>
  7.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8.  
  9.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  10.     <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11.  
  12.     <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  13.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  14.     <style>
  15.         html, body{
  16.             min-height:100%;
  17.             width:100%;
  18.         }
  19.         .table-holder{
  20.             width:100%;
  21.             max-height:65vh;
  22.             overflow:auto;
  23.         }
  24.         .table>thead{
  25.             position:sticky;
  26.             top:0;
  27.             background:white;
  28.             z-index: 1;
  29.         }
  30.     </style>
  31. </head>
  32.     <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  33.         <div class="container">
  34.             <a class="navbar-brand" href="./">Handling Upload w/ Duplicate Filename</a>
  35.             <div>
  36.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  37.             </div>
  38.         </div>
  39.     </nav>
  40.     <div class="container-fluid px-5 my-3" id="SampleApp">
  41.         <div class="col-lg-6 col-md-10 col-sm-12 mx-auto">
  42.             <h3 class="text-center"><b>Handling Upload w/ Duplicate Filename in PHP</b></h3>
  43.             <div class="d-flex w-100 justify-content-center">
  44.                 <hr class="w-50">
  45.             </div>
  46.            
  47.         </div>
  48.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
  49.             <div class="card rounded-0 shadow" id="dataSheetCard">
  50.                 <div class="card-header rounded-0">
  51.                     <div class="d-flex w-100 justify-content-between">
  52.                         <div class="col-auto flex-shrink-1 flex-grow-1">
  53.                             <div class="card-title">Upload Form</div>
  54.                         </div>
  55.                        
  56.                     </div>
  57.                 </div>
  58.                 <div class="card-body rounded-0">
  59.                     <div class="container-fluid">
  60.                         <form action="upload.php" method="POST" enctype="multipart/form-data" id="upload-form">
  61.                             <div class="mb-3">
  62.                                 <label for="upload" class="form-label">Choose File</label>
  63.                                 <input class="form-control form-control-sm" id="upload" name="upload" type="file">
  64.                             </div>
  65.                             <div class="mb-3">
  66.                                 <div class="d-grid">
  67.                                     <button class="btn btn-primary rounded-pill">Upload</button>
  68.                                 </div>
  69.                             </div>
  70.                         </form>
  71.                     </div>
  72.                 </div>
  73.             </div>
  74.         </div>
  75.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
  76.             <div class="card rounded-0 shadow" id="dataSheetCard">
  77.                 <div class="card-header rounded-0">
  78.                     <div class="d-flex w-100 justify-content-between">
  79.                         <div class="col-auto flex-shrink-1 flex-grow-1">
  80.                             <div class="card-title">Uploaded Files</div>
  81.                         </div>
  82.                        
  83.                     </div>
  84.                 </div>
  85.                 <div class="card-body rounded-0">
  86.                     <div class="container-fluid">
  87.                         <?php
  88.                        $files = [];
  89.                        if(is_dir("uploads/")){
  90.                            $files = scandir("uploads");
  91.                        }
  92.                        unset($files[0]);
  93.                        unset($files[1]);
  94.                        asort($files);
  95.                        ?>
  96.                         <div class="list-group">
  97.                             <?php foreach($files as $file): ?>
  98.                                 <a href="uploads/<?= $file ?>" class="list-group-item list-group-item-action" target="_blank"><?= $file ?></a>
  99.                             <?php endforeach; ?>
  100.                         </div>
  101.                     </div>
  102.                 </div>
  103.             </div>
  104.         </div>
  105.     </div>
  106.     <script src="app.js"></script>
  107. </body>
  108. </html>

Upload API

Here's the snippet that handles the upload files. The script contains a PHP Script like the one I provided above for handling the files with duplicate filenames on the upload directory.

  1. <?php
  2.  
  3. if($_SERVER['REQUEST_METHOD'] == "POST"){
  4.     if(isset($_FILES['upload']) && !empty($_FILES['upload'])){
  5.         //Upload files directory
  6.         $dir = "uploads/";
  7.  
  8.         //Create Upload Directory If not existing yet
  9.         if(!is_dir($dir))
  10.         mkdir($dir);
  11.  
  12.         // Get file's path info
  13.         $filepath_info = pathinfo($_FILES['upload']['name']);
  14.  
  15.         //filename
  16.         $filename = $filepath_info['filename'];
  17.  
  18.         // File Extension
  19.         $extension = $filepath_info['extension'];
  20.  
  21.         // Iteration starting Value
  22.         $i = 0;
  23.  
  24.         while(true){
  25.             // Filename additional text
  26.             $additional_txt = ($i>0) ? " ({$i})" : "";
  27.  
  28.             // Temporary new filename
  29.             $tempname = $filename.$additional_txt.".".$extension;
  30.  
  31.             // Cheching Filename Duplicate
  32.             if(is_file($dir.$tempname)){
  33.                 // If has duplicate
  34.                 $i++;
  35.             }else{
  36.                 // Renew Filename
  37.                 $filename = $tempname;
  38.                 // break the loop
  39.                 break;
  40.             }
  41.         }
  42.  
  43.  
  44.         // Upload file
  45.         $upload = move_uploaded_file($_FILES['upload']['tmp_name'], $dir.$filename);
  46.  
  47.         if($upload){
  48.             // If uploading file is successful
  49.             echo "<script> alert(`File has been uploaded successfully.`); location.replace('./') </script>";
  50.         }
  51.         else{
  52.             // If Uploading File fails
  53.             echo "<script> alert(`File uploading failed due to some reason.`); location.replace(document.referer) </script>";
  54.         }
  55.     }
  56. }else{
  57.     echo "<script> alert(`The request was not executed using POST Method.`); location.replace(location.referer)</script>";
  58. }
  59.  
  60. ?>

Snapshots

Here is the snapshot of the page interface using the snippet I provided above.

Handling Uploaded files with duplicate filenames

That's it! You can now test the sample web application using the snippets that I provided above and see if it achieves the objectives of this tutorial. I also provided the source code zip file of the snippets on this article page. You can download it by clicking the Download button below this article.

That's the end of this tutorial. I hope this Handling Uploaded files with duplicate filenames on the upload directory in PHP Tutorial helps you with what you are looking for and that you'll find this useful for your tutorial.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment