There is a script that counts the number of files in a folder, and, based on the calculations, assigns a unique id (int) to the file name.

That is, if there are 39 files, then 40 is written into the variable, then a file is created there and the total number of files already becomes 40.

$number = $i; // сюда записывается результат подсчета файлов в папке $text='example'; $format='.php'; $fulltext.= $text . $number . $format; //получилось example40.php 

After the full operation, the text is added to the main file in the list of the form:

 ... example37.php example38.php example39.php example40.php 

And in case of deletion from the middle of the list, for example : example38.php and deleting its file

After the file counting procedure is repeated, the script counts again 39 files in the folder, then adds +1 to the counting and writes it to the main file, and we get a line like

...

 example37.php example39.php example40.php example40.php 

Any idea how to solve the problem? Here is the counting script

// Counting the number of files in the content folder

  $path = 'content'; $dir = opendir ("$path"); $i = 0; while (false !== ($file = readdir($dir))) { if (strpos($file, '.txt',1) ) { $i++; } } $i++; $number = $i; 
  • use an absolutely random file name, or look for the maximum entry in the names of existing ones - etki
  • Absolutely random name guessed, trying to implement through rand (0, 900), in more detail about the maximum occurrence of existing ones? - hovdev
  • md5 hash content but why? - Naumov

3 answers 3

string tempnam ( string $dir , string $prefix )

Creates a file with a unique name in a specific directory ...

http://php.net/manual/ru/function.tempnam.php

    You can generate a unique file name, for example, like this:

     $dir = __DIR__; //путь до нужной папки do { $filename = md5(microtime(1).'-'.rand(0,500)) } while (file_exists($dir.'/'.$filename); 

    If you need to solve questions about the unique names of the mask, such as example23.php , then you can:

     $dir = __DIR__; //путь до нужной папки $files = glob($dir.'/example*.php'); $fileLast = end($files); preg_match('/example([\d]+).php/s', $fileLast, $match); $fileNew = $dir.'/example'.($match[1]+1).'.php'; 

    I do not pretend to be the most optimized or ideal solutions. But quite a working option.

      The script separates the last number from the file name and adds 1 to the maximum one available.

      Works with any extensions and file names that do not even contain numbers.

       $path = 'content'; $dir = opendir ($path); $keys = array(); while (false !== ($file = readdir($dir))) { if (preg_match("/[^\d](?P<number>\d+)\.\w+$/", $file, $matches)) { $key = $matches['number']; } else { $key = 0; } $keys[] = $key; } sort($keys); $maxKey = end($keys); echo $maxKey+1; // Выведет необходимое число для следующего имени файла