The upload script that I'm using works successfully, but if a file is uploaded that has the same name as a file that is already in the destination folder, the new file will overwrite the existing file. I'm looking for a simple solution to remedy this, like modifying the uploaded file name, like something with: $randomString = time(); Code (markup): Here's part of the current upload code: if (@$_POST['submit'] != "") { $allowed_ext = array("gif", "jpeg", "jpg", "png", "pdf", "doc", "docs", "zip", "mov", "MOV", "flv", "mp4", "3gp", "3GP"); $extension = end(explode(".", $_FILES["file"]["name"])); if (($_FILES["file"]["size"] < 10485760000) && in_array($extension, $allowed_ext)) { if ($_FILES["file"]["error"] > 0) { //$message.="There is some error in upload, see: " . $_FILES["file"]["error"] . "<br>";//Enable this to see actual error $message.="There is some error in upload. Please try after some time."; } else { $uploaddir = '../Upload/'; $uploadfile = $uploaddir . basename($_FILES['file']['name']); $uploaded_file = false; if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) { $uploaded_file = $_FILES['file']['name']; } Code (markup): Any help will be appreciated.
Or an alternate, with a file exists check: $uploadfile = $uploaddir . basename($_FILES['file']['name']); if(file_exists($uploadfile )){ $uploadfile = $uploaddir time().'_'.. basename($_FILES['file']['name']); }
I usually just check to see if the file exists (open it with errors trapped). If it does, throw the user a message about changing the name of the file s/he's uploading.
Why throw an error to the user? You can rename it yourself something(1).jpg something(2).jpg etc... Also, any specific reason to open and trap? I think almost all programming languages today have a fileExists check function available
You could, but if the user needs to know the name of the file, to look at it later, you'd have to send a message with the new name anyway. It depends on whether anyone is going to need the file in the future.
Normally, if a user needs access to the file, that doesn't happen with a direct link. Normally, you'd have an interface showing all files in the user's account, or in a folder, or something like that, giving the user the ability to get to the file regardless of what it's called. Of course, you would keep the submitted filename with a counter on the end, or something - but that is basically the same thing most OSes does with auto-renaming.