How to increment the filename txt that will be created in php?

4

If it is possible, how to increment the filename txt in php? I am working with php that I know very little, I need to increment the name of a txt file, so that a new json.txt file is created whenever I send a file to the server. Does anyone know how to do this? I'm having to increment on the hand, I'm in json46.txt .

$file = fopen('JSON46.txt', 'w'); // cria o arquivo json.txt
fwrite($file, $_POST['json']."\r\n\r\n\r\n");
    
asked by anonymous 12.06.2015 / 21:40

2 answers

1

It would be something like this:

//Primeiro você precisa de uma variável que conte.
$jsonIncremento = 0;

//aqui você concatena com o nome do arquivo.
$file = fopen('JSON' .$jsonIncremento. '.txt', 'w'); // cria o arquivo json.txt
fwrite($file, $_POST['json']."\r\n\r\n\r\n");

//depois a cada arquivo criado é so ir incrementando ela.
$jsonIncremento++;
    
12.06.2015 / 21:51
1

If you do not have a memory control of which number you need, I thought of the following solution:

  • Read all files in a directory.
  • I make regex to get all numbers in the title.
  • I'm looking for the largest number of them
  • Return the next increment you need


$seuDiretorio = '/tmp'; /* exemplo */
$arqs = scandir($seuDiretorio);

$maior = 0;
foreach ($arqs as $arq) {
    $numeroArq = preg_replace( '/[^0-9]/', '', basename($arq));

    if ($numeroArq > $maior) {
        $maior = $numeroArq;
    }
}

echo 'Próximo Numero é '. ($maior + 1);

This way to create the next one is just to do:

$file = fopen('JSON'.($maior+1).'.txt', 'w');

With this code you need to be aware that in the directory you can only have the files you are saving.

    
12.06.2015 / 21:55