The data in <textarea name="textblock"></textarea> is saved in a text file textfile.txt with this script:

 <?php // Открыть текстовый файл $f = fopen("title/textfile.txt", "w"); // Записать текст fwrite($f, $_POST["textblock"]); // Закрыть текстовый файл fclose($f); // Открыть файл для чтения и прочитать строку $f = fopen("title/textfile.txt", "r"); // Читать текст echo fgets($f); fclose($f); ?> 

But at the same time, each new entry overwrites the previous one. How to register so that each new entry occurs in a new file (1.txt, 2.txt, 3.txt, ...)?

  • And why do you read the contents of the file again after writing to the file? Do you think it will be different from what is contained in $_POST["textblock"] ? - Johny
  • one
    This is apparently a check. Suddenly nothing was written to the file. Exceptions? Did not hear ... - LTKH

2 answers 2

The simplest solution:

 <?php //определяем имя файла $file_name = "title/" . strval(count(glob('./title')) + 1) . ".txt"; // Открыть текстовый файл $f = fopen($file_name, "w"); ... 

glob('./title') - here instead of './title' write the path to the directory where your files are stored.

But in your place I would choose the file name so that it contains the date:

 <?php //создаем объект DateTime с текущей датой $date = date_create(); //определяем имя файла $file_name = "title/" . date_format($date, 'YmdHis.u') . ".txt"; // Открыть текстовый файл $f = fopen($file_name, "w"); ... 

    Change w to a or a+

    New records will be recorded in one file and will not overwrite previous ones.

    • 'r' - open only for reading, puts the pointer to the beginning of the file;
    • 'r +' - open for reading and writing, puts the pointer to the beginning of the file;
    • 'w' - open for writing only, put a pointer to the beginning of the file and clear the entire contents of the file; if the file does not exist, a new file is created;
    • 'w +' - open for reading and writing, puts a pointer to the beginning of the file and clears the entire contents of the file; if the file does not exist, a new file is created;
    • 'a' - open for writing only, puts a pointer to the end of the file, if the file does not exist, a new file is created;
    • 'a +' - open for reading and writing, puts the pointer to the end of the file, if the file does not exist, a new file is created.