-1

I am try to writing PHP code that generate unique file name.

First of all it will check if first given name file 'Vector background' exits or not in folder .If yes it will add 1 in last so file name will be 'Vector background 1' so it will check again if yes than ad one i last so new name will be 'Vector background 11' it will do while it will get unique name.

i try my self

$folder='C:\Users\Desktop\file exits\\';
$name='log';

$result=file_exists($folder.$name);
if ($result == "1") {  //// file exits so work start
///// generate name file that not exists in folder
$name=$name.' 1';
$result=file_exists($folder.$name);

if ($result == "1") {
$name=$name.' 1';
$result=file_exists($folder.$name);
}

}

well that is my progress it is not smart code

Yaldram
  • 99
  • 1
  • 1
  • 11

1 Answers1

2

First you can rewrite the code so that your "naming" algorithm lives inside a loop.

$fname = $folder . $name;
while (file_exists($fname)) {
    $fname = $fname . '1';
}

However, this code is not very efficient and can potentially make you run into issues. For instance, the filepath can exceed the maximum number of characters allowed by the OS.


If what you're trying to achieve is just a unique filename to prevent filename collisions, PHP has a built in function called tempnam. It creates a file with a unique filename, with access permission set to 0600, in the specified directory.

string tempnam ( string $dir, string $prefix )

so your code can be rewritten like this:

$fname = tempname($folder, $name);
Barry
  • 3,303
  • 7
  • 23
  • 42
Tivie
  • 18,864
  • 5
  • 58
  • 77