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.
- <?php
- $dir = "uploads/";
- // Get file's path info
- //filename
- $filename = $filepath_info['filename'];
- // File Extension
- $extension = $filepath_info['extension'];
- // Iteration starting Value
- $i = 0;
- while(true){
- // Filename additional text
- $additional_txt = ($i>0) ? " ({$i})" : "";
- // Temporary new filename
- $tempname = $filename.$additional_txt.".".$extension;
- // Cheching Filename Duplicate
- // If has duplicate
- $i++;
- }else{
- // Renew Filename
- $filename = $tempname;
- // break the loop
- break;
- }
- }
- // Upload file
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.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <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>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- .table-holder{
- width:100%;
- max-height:65vh;
- overflow:auto;
- }
- .table>thead{
- position:sticky;
- top:0;
- background:white;
- z-index: 1;
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3" id="SampleApp">
- <div class="col-lg-6 col-md-10 col-sm-12 mx-auto">
- <div class="d-flex w-100 justify-content-center">
- <hr class="w-50">
- </div>
- </div>
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
- <div class="card rounded-0 shadow" id="dataSheetCard">
- <div class="card-header rounded-0">
- <div class="d-flex w-100 justify-content-between">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- </div>
- </div>
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form action="upload.php" method="POST" enctype="multipart/form-data" id="upload-form">
- <div class="mb-3">
- <input class="form-control form-control-sm" id="upload" name="upload" type="file">
- </div>
- <div class="mb-3">
- <div class="d-grid">
- </div>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto mb-3">
- <div class="card rounded-0 shadow" id="dataSheetCard">
- <div class="card-header rounded-0">
- <div class="d-flex w-100 justify-content-between">
- <div class="col-auto flex-shrink-1 flex-grow-1">
- </div>
- </div>
- </div>
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <?php
- $files = [];
- if(is_dir("uploads/")){
- $files = scandir("uploads");
- }
- unset($files[0]);
- unset($files[1]);
- asort($files);
- ?>
- <div class="list-group">
- <?php foreach($files as $file): ?>
- <?php endforeach; ?>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </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.
- <?php
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- //Upload files directory
- $dir = "uploads/";
- //Create Upload Directory If not existing yet
- // Get file's path info
- //filename
- $filename = $filepath_info['filename'];
- // File Extension
- $extension = $filepath_info['extension'];
- // Iteration starting Value
- $i = 0;
- while(true){
- // Filename additional text
- $additional_txt = ($i>0) ? " ({$i})" : "";
- // Temporary new filename
- $tempname = $filename.$additional_txt.".".$extension;
- // Cheching Filename Duplicate
- // If has duplicate
- $i++;
- }else{
- // Renew Filename
- $filename = $tempname;
- // break the loop
- break;
- }
- }
- // Upload file
- if($upload){
- // If uploading file is successful
- echo "<script> alert(`File has been uploaded successfully.`); location.replace('./') </script>";
- }
- else{
- // If Uploading File fails
- echo "<script> alert(`File uploading failed due to some reason.`); location.replace(document.referer) </script>";
- }
- }
- }else{
- echo "<script> alert(`The request was not executed using POST Method.`); location.replace(location.referer)</script>";
- }
- ?>
Snapshots
Here is the snapshot of the page interface using the snippet I provided above.
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
- 889 views