Stooney Posted December 23, 2007 Share Posted December 23, 2007 I'm having a problem where when uploading a file with the same name as one already uploaded this script won't append numbers properly. Say I want to upload bike.jpg but it already exists. Well the script will rename it to 1-bike.jpg. That works, but if 1-bike.jpg already exists it will overwrite it instead of incrementing to 2-bike.jpg. It will always stop at 1 and continue to uploading. Any ideas? <?php if(isset($_FILES['userfile']) && $_POST['dname']!="!e" && $_POST['dname']!="!r"){ $uploaddir = "../dtf_files/"; $_FILES['userfile']['name']=ereg_replace(" ", "_", $_FILES['userfile']['name']); $uploadfile = $uploaddir.basename($_FILES['userfile']['name']); $filename=$_FILES['userfile']['name']; if(file_exists($uploadfile)){ $tmpVar=1; while(file_exists(basename($uploaddir.$tempVar.'-'.$_FILES['userfile']['name']))){ $tmpVar++; } $filename=$tmpVar.'-'.$_FILES['userfile']['name']; $uploadfile=$uploaddir.$tmpVar.'-'.$_FILES['userfile']['name']; } if(move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)){ $size=$_FILES['userfile']['size']; $type=$_FILES['userfile']['type']; $dname=mysql_real_escape_string($_POST['dname']); $category=mysql_real_escape_string($_POST['category']); $store=mysql_query("INSERT INTO dtf_files (dname, fname, path, size, dateadded, type, categoryid) VALUES ('$dname', '$filename', '$uploaddir', '$size', NOW(), '$type', '$category')"); if(mysql_affected_rows()==1){ $_POST['dname']="!r"; upload_file(); } else{ $uerror="<p>SERVER ERROR: Failed inserting data into database!</p>"; $_POST['dname']="!e"; upload_file(); } } else{ echo "<p>SERVER ERROR: Failed uploading file!</p>"; } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/82909-solved-upload-script-overwriting-same-name-files/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.