File Upload Without Overwriting Existing Files of Same Name in PHP
While creating a file upload function for a website, there is always a possibility that it will overwrite an existing file with same on the server. You can overcome this problem by checking if the file with the same name already exist or not. If File already exists with same name, you can then change the name of the file you are uploading. You can simply add number prefix for this.
In the below code snippet, we will see how to rename a file in case of another file with same name exists on the server.
HTML Code for File Upload
<html> <head> <title>HTML Form for uploading image to server</title> </head> <body> <form name="upload" method="post" action="uploadresults.php" enctype="multipart/form-data"> <input type="file" name="Image"><br> <input type="submit" value="Upload Image"> </form> </body> </html>
uploadresults.php
Now this file upload and save file on server. To avoid overwriting of any existing file, you need to put a random name of this file which is almost impossible to be available as a file name in the server. Other way is to check if file is already available and then add a counter number in the file name. In this below code, we are checking the file name and then adding the counter in the file name.
<?php // rename file to remove unfriendly characters $OriginalFilename = $FinalFilename = preg_replace('`[^a-z0-9-_.]`i','',$_FILES['image']['name']); // rename file if it already exists by prefixing an incrementing number $FileCounter = 1; // loop until an available filename is found while (file_exists( 'files/'.$FinalFilename )) $FinalFilename = $FileCounter++.'_'.$OriginalFilename; move_uploaded_file ( $_FILES['image']['tmp_name'], "files/$FinalFilename" ) or die ("Could not copy"); ?>
You can also overcome this problem by adding timestamp in the name of each files before upload.
This was a very basic file upload example to avoid the overwriting of existing file.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.