0

i need to change variable data if the 'data name' already exists..

i have this

if (file_exists('../../images/produtos/'.$name)){
        $name = '1_'.$name;
    }

it is working, if i have a file with the name that is saved in the variable $name, it create a new one with a 1_ before, but i need to check if there is a 1_.$name, 2_$name ...... until there is no file with the name saved in variable $name.

If i upload a file with name things.png i need to check if there is already a file called things.png, if there is then change a name to 1_things.png, but if there is a file called 1_things.png change the name to 2_things.png etc etc until there is no file with the same name.

PS: I dont want overwrite obv..

Im sorry for my bad english, but i really dont know how to explain this better, hope you guys understand.

Thanks in advance

3
  • 2
    Why not rename all the files and add a random string or date at the end of the original file name? Eg. piano.png to piano1234.png That way you dont have to worry about duplicate file names.
    – Abu Nooh
    Apr 6, 2014 at 1:22
  • @MarioSegura Segura Sorry its $name not $nome, and yes, name is saving a typo.
    – DELETE ME
    Apr 6, 2014 at 1:28
  • @abushahin Thats okay, but how can i check if there is already a piano1, a piano12, etc ? Sorry i am starting :S
    – DELETE ME
    Apr 6, 2014 at 1:28

1 Answer 1

5

Use a loop:

if(file_exists('../../images/produtos/'.$name)){
$i = 1;
    while(file_exists('../../images/produtos/'.$i."_".$name)){
    $i++;
    }
$name = $i."_".$name;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.