There is a code that adds lines to the file, but at the end of the file, and how to do what would add to the beginning of the file? And I also wanted to know if there is a way to add it to the 2nd line of the file?

<?php if ($_POST['']); $name = htmlspecialchars($_POST['name']); $link = htmlspecialchars($_POST['link']); $space = ' '; // строка, которую будем записывать со всеми переносами $text = "$name\n$link\n$space\n"; // открываем файл, если файл не существует, делается попытка создать его $fp = fopen("abc.txt", "a+"); // записываем fwrite($fp, $text); // закрываем fclose($fp); echo 'Данные записаны'; ?> 
  • Create a new file. Copy the first n lines from the old file into it, write m new lines there, copy the remaining lines from the old file. Delete old file, rename new to old. - Sergey
  • Are there any php memory mapped files? Then you can try to reduce the task to simply moving arrays of bytes (and possibly much more complex objects) from one memory address to another. - Sergey
  • The file system allows you to add only to the end, it is a physical limitation. But you can always overwrite the entire file. From the point of view of the file system, there is no concept of lines, so no, it is impossible to directly write to some line, it is possible to operate only with a position inside the file. - etki

3 answers 3

I'm afraid the indication of the "c +" mode will not help much, since the data will not be appended, but overwritten at the beginning of the file. At least in my case.

I would recommend this solution:

 $text = "ваш текст"; $text .= file_get_contents("abc.txt"); //читаем и "дописываем" в начало текста file_put_contents("abc.txt", "\xEF\xBB\xBF". $text ); //записываем обратно c BOM согласно комментарию 
  • How to make sure that the quote does not change but remains Utf-8? - arthru
  • It depends on what problems you have there. Here are enough solutions: stackoverflow.com/questions/4839402/… . Well, once there is such a problem, make sure that you have the script and the file in utf-8. - Gino Pane
  • That's what I did - utf-8 quotes everywhere, but then when something is added to the file, it will automatically become urf-8 without bom codepen.io/anon/pen/rLLqvN - arthru
  • Well, you, apparently, 3 bytes bom constantly overwrite. Under the link specified by me too. - Gino Pane
  • You can insert it into the code, but I can’t figure it out. - arthru

Specify mode "c +" (the file pointer will be set to the beginning of the file): $fp = fopen("abc.txt", "c+");

And in order to set a pointer to a given position, you need to use fseek , only for this you need to count the number of bytes (not characters) by which you need to move the pointer.

    You can write to the beginning through the mode for fopen - c+ , as noted by @VladVlad.
    But if you need to add / rewrite a specific line, then it is easier like this:

     $str = 'myString'; // Строка $file = file('1.txt'); // Читаем файл в массив: 1 элемент - одна строка // Пишем в начало: добавляем строку с \n в начало (0 позиция) массива строк array_unshift($file, $str . "\n"); // Заменить строку: меняем элемент массива с индексом [N-строки - 1] (с нуля же считаем) // Оригинальную строку очищаем trim'ом, там в конце \n лишний // В конце добавляем опять \n, чтобы строки не слиплись :) $file[1] = trim($file[1]) . $str . "\n"; // Сливаем массив в строку и записываем его обратно file_put_contents('1.txt', implode("", $file));