This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
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.
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 withimplode()
in order to write the data to a file. -
flags
: controls the behavior offile_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 function file_put_contents()
is to overwrite the contents of a given file with any new data the you provide. This is not desirable when you want to preserve the old data and and new one. 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()
.
<?php // 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.
Keep in mind the this function will create a file if one doesn't already exist. However, it won't create a non-existing 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 file that you want to open. -
mode
: the mode for opening a file can be specified using either one or two characters. Since, we want to open the file and then append some text to it. To append, set the mode with the charactera
ora+
. 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 thea+
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 withfopen()
. -
string
: the text that you want to append 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.
Here is an example that shows you how to use fopen()
, fwrite()
and fclose()
to append data to a file.
<?php $square_file = fopen("squares.txt", "a+"); //output the squares from 1 to 10 for($i = 1; $i <= 10; $i++) { $square = $i*$i; $cube = $square*$i; $line = "Square of $i is: $square.\n"; fwrite($square_file, $line); } fseek($square_file, 0) echo fgets($square_file) fclose($square_file); ?>
Square of 1 is: 1. Square of 2 is: 4. Square of 3 is: 9. Square of 4 is: 16. Square of 5 is: 25. Square of 6 is: 36. Square of 7 is: 49. Square of 8 is: 64. Square of 9 is: 81. Square of 10 is: 100.
In this case, we are writing the square of numbers 1 to 10 in a file called square.txt. We opened it using the fopen()
function in a+
mode which means we can also read content from the file as well appending our own content. A new line with the current value of $i
and its square is appended to our file with each iteration of the for loop.
There are a few functions like fread()
and fgets()
that you could use to read whatever is written inside the file. However, you will usually need to use fseek()
to place the file pointer at the desired position to read the data as expected. After the loop, we seek to the beginning of the file and read it's first line with fgets()
.
Finally, we close the handle to our file by calling the function fclose()
.
Final Thoughts
In this tutorial, we learned two different methods of appending data to a file with PHP. Using the file_put_contents()
function is more convenient for writing data to a file. However, using fwrite()
can be more efficient when you have to do multiple write operations on a file. Opening a file with fopen()
to append the data also gives you the option to read its contents by moving the file pointer to desired location.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Monty Shokeen
Monty Shokeen | Sciencx (2021-08-14T03:47:47+00:00) How to Append to a File With PHP. Retrieved from https://www.scien.cx/2021/08/14/how-to-append-to-a-file-with-php/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.