Loop to increment duplicate filenames

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Loop to increment duplicate filenames

Post 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
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: Loop to increment duplicate filenames

Post 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
            }
   
        }
    }
 
Post Reply