Quote:
|
...and just need to know how to check whether a filename already exists or not before uploading it, and if it does exist, then upload the file with a different filename.
|
Once the submit button on a file-type form is pressed the file will be uploaded (hopefully with success) to a temporary location on the server. Checking if the file name already exists and naming it differently before moving it from the temp location to the final location is fairly easy.
If you literally want to check if the file name exists
before uploading it, you would need to make a "file name verification form", that just submits the file name. Your code would then check to see if the name exists. If it does, you would loop back and ask the user to enter another name (or you could automate this by adding a prefix or suffix to the 1st name and increment it until you find a file name that does not exist.) Once you have a file name that does not exist, you would use PHP to place this name into the VALUE= part of the file name field in the actual file upload form.
---------------- don't read below this line unless you are sitting down and have a health heart

--------------------
If you have multiple users uploading into the same folder, I can see the possibility with both the "before" and "after" methods of checking for a duplicate file name that between the time you check if a file name exists and when you move the temporary file to the final location/name, that someone else could have uploaded a file with the same name.
The fix for both of the methods would be the same. Instead of using the file_exists() function, you would need to fopen the file for append "a." This will either open an existing file or create a new one. Use the filesize() function to find the size of the resultant file. If it is zero, then the file did not pre-exist, but it does now (reserving the file name.)
This file name reservation problem will be more pronounced if you use the method where you check if the file name exists before the upload, due to the time it will take for the upload to happen. It could take several seconds to several minutes for the upload to occur. If the file name is not reserved, someone else could upload a shorter file with the same name. Then when the code attempts to save the file that took longer, it will be faced with a duplicate file name.
Does this seam complex - yes. But that is life when you can have multiple concurrent users trying to save files to one location. You could of course leave this file name reservation logic out and live with an occasionally overwritten file.