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. html, body{
  15. min-height:100%;
  16. width:100%;
  17. }
  18. .table-holder{
  19. width:100%;
  20. max-height:65vh;
  21. overflow:auto;
  22. }
  23. .table>thead{
  24. position:sticky;
  25. top:0;
  26. background:white;
  27. z-index: 1;
  28. }
  29. </style>
  30. </head>
  31. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  32. <div class="container">
  33. <a class="navbar-brand" href="./">Handling Upload w/ Duplicate Filename</a>
  34. <div>
  35. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  36. </div>
  37. </div>
  38. </nav>
  39. <div class="container-fluid px-5 my-3" id="SampleApp">
  40. <div class="col-lg-6 col-md-10 col-sm-12 mx-auto">
  41. <h3 class="text-center"><b>Handling Upload w/ Duplicate Filename in PHP</b></h3>
  42. <div class="d-flex w-100 justify-content-center">
  43. <hr class="w-50">
  44. </div>
  45.  
  46. </div>
  47. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
  48. <div class="card rounded-0 shadow" id="dataSheetCard">
  49. <div class="card-header rounded-0">
  50. <div class="d-flex w-100 justify-content-between">
  51. <div class="col-auto flex-shrink-1 flex-grow-1">
  52. <div class="card-title">Upload Form</div>
  53. </div>
  54.  
  55. </div>
  56. </div>
  57. <div class="card-body rounded-0">
  58. <div class="container-fluid">
  59. <form action="upload.php" method="POST" enctype="multipart/form-data" id="upload-form">
  60. <div class="mb-3">
  61. <label for="upload" class="form-label">Choose File</label>
  62. <input class="form-control form-control-sm" id="upload" name="upload" type="file">
  63. </div>
  64. <div class="mb-3">
  65. <div class="d-grid">
  66. <button class="btn btn-primary rounded-pill">Upload</button>
  67. </div>
  68. </div>
  69. </form>
  70. </div>
  71. </div>
  72. </div>
  73. </div>
  74. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
  75. <div class="card rounded-0 shadow" id="dataSheetCard">
  76. <div class="card-header rounded-0">
  77. <div class="d-flex w-100 justify-content-between">
  78. <div class="col-auto flex-shrink-1 flex-grow-1">
  79. <div class="card-title">Uploaded Files</div>
  80. </div>
  81.  
  82. </div>
  83. </div>
  84. <div class="card-body rounded-0">
  85. <div class="container-fluid">
  86. <?php
  87. $files = [];
  88. if(is_dir("uploads/")){
  89. $files = scandir("uploads");
  90. }
  91. unset($files[0]);
  92. unset($files[1]);
  93. asort($files);
  94. ?>
  95. <div class="list-group">
  96. <?php foreach($files as $file): ?>
  97. <a href="uploads/<?= $file ?>" class="list-group-item list-group-item-action" target="_blank"><?= $file ?></a>
  98. <?php endforeach; ?>
  99. </div>
  100. </div>
  101. </div>
  102. </div>
  103. </div>
  104. </div>
  105. <script src="app.js"></script>
  106. </body>
  107. </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