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

Asked

Viewed 481 times

4

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

$file = fopen('JSON46.txt', 'w'); // cria o arquivo json.txt
fwrite($file, $_POST['json']."\r\n\r\n\r\n");
  • 2

    You want to change the name of the same file?

  • I want to generate files incrementing the number in the name for example Json1.txt after Json2.txt always incrementing the number.

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++;

1

If you don’t have a memory control of which number you need, I thought of the following solution:

  • Read all files from a directory.
  • I make a regex to get all numbers in the title.
  • I look for the greatest number among 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 is just to do:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.