Page 1 of 1

Loop to increment duplicate filenames

Posted: Tue Jun 02, 2009 5:47 am
by mattpointblank
I'm trying to prevent users submitting files with the same filename. My code is structured to create an array of existing filenames from the database, compare these to the one being entered, and add a number if the name already exists. I thought I'd created it properly, but found a slight issue - I now have files named like this:

filename
filename1
filename12
filename123
filename1234
// etc

What I actually wanted was something more like:

filename
filename1
filename2
filename3
filename4
// etc


This way, names will be shorter etc. Here's the code I used to produce the above:

Code: Select all

 
$name_exists = true;
$i=1;
//$existing_names contains an array of filenames
//$productName is taken from $_POST input
 
    while($name_exists == true) {
    
        foreach($existing_names as $name)
        {   
            if($name == $productName) {
                    // add a number to the end, then try that
                $productName = $productName.$i;
                $i++;
            } else {
                $name_exists = false; // so we can use this name as it exists
            }
    
        }
    }
 
It's obvious how this happened, but my issue is figuring out a better way to increment the counter. Like, I could just run some code to trim the number from the end of the filename and then begin incrementing again, but what if the original filename contains a number? Is there a simpler way to do this kind of thing?

Thanks
Matt

Re: Loop to increment duplicate filenames

Posted: Tue Jun 02, 2009 6:39 am
by susrisha
hey matt.. try this

Code: Select all

 
$name_exists = true;
$i=1;
//$existing_names contains an array of filenames
//$productName is taken from $_POST input
$basename=$productName;
 
    while($name_exists == true) {
   
        foreach($existing_names as $name)
        {   
            if($name == $productName) {
                    // add a number to the end, then try that
                $productName = $basename.$i;
                $i++;
            } else {
                $name_exists = false; // so we can use this name as it exists
            }
   
        }
    }