Append to file with php

How to append data to a file in PHP

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

In PHP scripts, there are times when you need to save data. Depending on the type of data and what you may want to do with it later, you can store it in either:

In this shot, we will learn how to add more data to the content of a text file.

How to append data to a text file in PHP

To append or add more data to a file, you can follow the steps listed below.

Step 1

Identify the file to be written to. For example, you may want to append data to a file named append.txt .

Step 2

Open this file in your script with the fopen() function.

Pass the file’s name and the mode with which you want to open the file as arguments to the fopen() function.

In this case, the mode will be the append mode, indicated by a .

$appendVar = fopen('append.txt','a'); 

Note: Make sure the correct file path is indicated while writing the file name.

Step 3

Write the new information that you have to add to the file. You can do this using the fwrite() function. For arguments, pass the variable containing the already opened file in append mode and the new set of information to be added.

fwrite($appendVar, 'So this the new line'); 

We can add more lines using the fwrite() function, as shown above.

Step 4

Close the text file. Use the fclose() function to do this, as shown below.

You can recheck your text file to see what you have added.

Code

Below is the complete code of the example we have been working through.

Источник

How to Append to a File With PHP

Monty Shokeen

Monty Shokeen Last updated Aug 14, 2021

Data is usually stored in a database when people are creating their website. However, sometimes we need to store data in files to make it easier for people to read or modify at a later time.

PHP comes with a lot of functions to read and write data to a file. We can also use a few of them to append data to a file. In this tutorial, you’ll learn two different ways of appending data to a file with PHP.

Читайте также:  Время работы алгоритма python

Understanding the file_put_contents() Function

The file_put_contents() function is one of the easiest ways to write data to a file with PHP. It accepts four different parameters that determine its behavior. These parameters are:

  • filename : the path to the location of the file to which we want to write our data.
  • data : specifies the data that you want to write to the file. It is usually a string, but you can also specify an array or a stream resource. The function will automatically implode the contents of a single dimensional array with implode() in order to write the data to a file.
  • flags : controls the behavior of file_put_contents() . There are three different flags that you can set here, either by themselves or in combination with other flags. Different flags can be combined using the | operator.
  • context : useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Using file_put_contents() to Append Data to a File With PHP

The default behavior of the file_put_contents() function is to overwrite the contents of a given file with any new data you provide. This is not desirable when you want to preserve the old data and add some new data. In such cases, you can use the FILE_APPEND flag to let PHP know that it should append data at the end of content originally present in the file.

Under some special circumstances, you might be appending data to a file from multiple scripts at the same time. In these situations, it is advisable to get an exclusive lock on the file using the LOCK_EX flag. This can help prevent data corruption or some other unexpected behavior. When you use this flag, other scripts will wait for the current process to complete writing to the file before they append their own data.

Here is an example in which some text is appended to an existing file using file_put_contents() .

// Original File: Canada is a country in North America. . bi-national land border. 
// File Contents After this Line: Canada is a country in North America. . bi-national land border. Canada's capital is Ottawa, 
file_put_contents('canada.txt', " Canada's capital is Ottawa,", FILE_APPEND | LOCK_EX); 
// File Contents After this Line: Canada is a country in North America. . bi-national land border. Canada's capital is Ottawa, and its three largest metropolitan areas are Toronto, Montreal, and Vancouver. 
file_put_contents('canada.txt', " and its three largest metropolitan areas are Toronto, Montreal, and Vancouver.", FILE_APPEND | LOCK_EX); 

In the above example, we wrote some strings to a file called canada.txt which contains information about Canada. Both the string were appended at the end of the file one after the other.

Читайте также:  Php защита от php include

Keep in mind that this function will create a file if one doesn’t already exist. However, it won’t create a non-existent directory. So it might be a good idea to check if a file exists before you start writing to it.

Using fwrite() to Write Data to a File With PHP

Using the file_put_contents() function to write data to a file with PHP is similar to calling fopen() , fwrite() , and fclose() in that order. This means that doing multiple write operations on the same file can be inefficient because we are constantly opening and closing the file again and again.

One way to overcome this issue is to call these functions yourself. Just begin by calling fopen() at the start of the write operation. After that, write content to the file as many times as you like with the fwrite() function. In the end, you can simply call fclose() to close the file handle. Let’s discuss each of these steps in detail now.

The fopen() function accepts four different parameters that you can use to tell PHP how it should open a file.

  • filename : the name of the file that you want to open.
  • mode : the mode for opening a file can be specified using either one or two characters. We want to open the file and then append some text to it. To append, set the mode with the character a or a+ . This will place the file pointer at the end of the file. PHP will also try to create the file if it doesn’t already exist. When files are opened with the a+ mode, you can also read the contents of the file.
  • use_include_path : instructs PHP to look for files inside the specified include path as well. Defaults to false.
  • context : useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Now that the file is open, we can use the fwrite() function to add information to the file. fwrite() takes three parameters:

  • resource : this is the resource handle we created earlier with fopen() .
  • string : the text that you want to append to your file.
  • length : is optional and it is used to set the maximum number of bytes that should be written to the file.

You can close the file handle by using the fclose() function once you have completed all your write operations.

Читайте также:  Css v34 zombie bot

Here is an example that shows you how to use fopen() , fwrite() , and fclose() to append data to a file.

Источник

file_put_contents

Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .

Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .

Список параметров

Путь к записываемому файлу.

Записываемые данные. Может быть string , array или ресурсом stream .

Если data является ресурсом stream , оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .

Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode(», $array)).

Значением параметра flags может быть любая комбинация следующих флагов, соединенных бинарным оператором ИЛИ (|).

Доступные флаги

Флаг Описание
FILE_USE_INCLUDE_PATH Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path.
FILE_APPEND Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать.
LOCK_EX Получить эксклюзивную блокировку на файл на время записи.

Корректный ресурс контекста, созданный с помощью функции stream_context_create() .

Возвращаемые значения

Функция возвращает количество записанных байт в файл, или FALSE в случае ошибки.

Эта функция может возвращать как boolean FALSE , так и не-boolean значение, которое приводится к FALSE . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.

Примеры

Пример #1 Пример простого использования

$file = ‘people.txt’ ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= «John Smith\n» ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>

Пример #2 Использование флагов

$file = ‘people.txt’ ;
// Новый человек, которого нужно добавить в файл
$person = «John Smith\n» ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND flag для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>

Список изменений

Версия Описание
5.1.0 Добавлена поддержка LOCK_EX и возможность передачи потокового ресурса в параметр data

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в Поддерживаемые протоколы и обработчики (wrappers).

Смотрите также

  • fopen() — Открывает файл или URL
  • fwrite() — Бинарно-безопасная запись в файл
  • file_get_contents() — Читает содержимое файла в строку
  • stream_context_create() — Создаёт контекст потока

Источник

Оцените статью