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
<title>HTML Form for uploading image to server</title>
<form name="upload" method="post" action="uploadresults.php" enctype="multipart/form-data">
<input type="file" name="Image"><br>
<input type="submit" value="Upload Image">
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.
// 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.