Jump to content

[SOLVED] upload script overwriting same name files


Recommended Posts

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>";
	}
}
?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.