- How to append data to a file in PHP
- How to append data to a text file in PHP
- Step 1
- Step 2
- Step 3
- Step 4
- Code
- How to Append to a File With PHP
- Understanding the file_put_contents() Function
- Using file_put_contents() to Append Data to a File With PHP
- Using fwrite() to Write Data to a File With PHP
- 2 Ways To Write & Append To Files In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP WRITE FILE EXAMPLES
- EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS
- EXAMPLE 2) WRITE & APPEND USING FOPEN
- EXAMPLE 3) ADDING NEW LINES
- EXAMPLE 4) WRITE ARRAY TO FILE, LINE-BY-LINE
- EXAMPLE 5) WRITING AN ARRAY TO CSV FILE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- SUMMARY
- LINKS & REFERENCES
- TUTORIAL VIDEO
- INFOGRAPHIC CHEAT SHEET
- THE END
- PHP Append Text to a File
- PHP Append Data to a File Example
- Now the content of file after appending is:
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 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.
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.
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.
Here is an example that shows you how to use fopen() , fwrite() , and fclose() to append data to a file.
2 Ways To Write & Append To Files In PHP (Simple Examples)
Welcome to a quick tutorial on how to write and append to files in PHP. Need to write some data to a file in your project?
- Write a string to a file.
- file_put_contents(«FILE.NAME», «DATA»);
- To append to an existing file, pass in an append flag – file_put_contents(«FILE.NAME», «DATA», FILE_APPEND);
- Open a file stream and write data to it.
- $fh = fopen(«FILE», «w») to create a new stream, or $fh = fopen(«FILE», «a») to append to an existing file.
- fwrite($fh, «STRING TO WRITE»);
- fclose($fh);
That should cover the quick basics, but read on if you need more examples!
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP WRITE FILE EXAMPLES
All right, let us now go into the various examples of how to write files in PHP.
EXAMPLE 1) WRITE TO FILES USING PUT CONTENTS
Yep, this is the most convenient fuss-free way to write to file in PHP – Just use the file_put_contents() function. But take note that it will override the file by default, remember to pass in FILE_APPEND if you want to append to the file instead.
EXAMPLE 2) WRITE & APPEND USING FOPEN
- $fh = fopen(«demo.txt», «w») opens a file stream to work with. Take note of the second “mode” parameter – w stands for “write”m and a stands for “append”. But of course, there are a lot more, I will leave a link to the official PHP manual below if you are interested.
- fwrite($fh, «STRING») writes to the file.
- fclose($fh) closes the file stream. It is highly recommended to do so because nobody likes a corrupted file.
So why do some “dumb people” go through all the trouble to use this “inconvenient” method? Simply because it offers a lot more controls, and performs way better when dealing with massive amounts of data.
EXAMPLE 3) ADDING NEW LINES
// (A) OPEN/CREATE FILE - LOOP & WRITE $fh = fopen("demo.txt", "w"); // (B) WRITE LINES fwrite($fh, "First line.\r\n"); fwrite($fh, "Second line.\r\n"); fwrite($fh, "Third line.\r\n"); // (C) DONE fclose($fh); echo "DONE!";
- When it comes to adding new lines, there are 2 “special characters” that you have to know: \r for “carriage return” and \n for “line feed”.
- Then comes the painful part – Linux uses \n , Mac uses \r , Windows uses \r\n . Read on Wikipedia if you are interested.
- Most code ninjas just shrug and use \r\n regardless, and it is kind of “universally understood” as a single line break.
EXAMPLE 4) WRITE ARRAY TO FILE, LINE-BY-LINE
// (C) DONE fclose($fh); echo "DONE!";
- We open a file using fopen() as usual.
- Then simply use foreach() to loop through the array.
- Use fwrite() to write each element to the file, line-by-line.
- Lastly, close the file properly with fclose() .
EXAMPLE 5) WRITING AN ARRAY TO CSV FILE
// (C) DONE! fclose($fh); echo "DONE!";
Here is the last example, and a small extra for you guys who are looking to generate reports or spreadsheets. Yes, there is a fputcsv() function that we can conveniently use to create CSV files.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
SUMMARY
LINKS & REFERENCES
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that this has helped you to better understand. If you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!
PHP Append Text to a File
To append text to a file in PHP, we need to process similar tasks as done when writing text to a file. The only thing we have to change is the file-opening mode.
Therefore, use either a or a+ mode.
The a mode is used to append data to a file, whereas the a+ mode is used to append data to a file along with the read function. That is, with a+, we can append the data, then use the rewind() or seek() functions to move the file pointer to any position in the file to read its content.
PHP Append Data to a File Example
After executing the above PHP example, the text or data PHP is Fun will get appended to the file named codescracker.txt. Here is the snapshot of the file, codescracker.txt, after executing the above PHP code:
You can use fwrite($fp, «\nPHP is Fun»); to append the text from a new line.
Note: The fopen() function opens a file.
Note: The fwrite() function is used to write content to a file.
Note: The fclose() function closes a file.
Let me create another example of appending the data to a file with some elaboration and modification based on the previous example:
The content of file is:"; while(!feof($fp)) < $line = fgets($fp); echo $line; echo "
"; > // appending the new data (two lines of text) to the file fwrite($fp, PHP_EOL); $x = "Yes, PHP is Fun!"; fwrite($fp, $x.PHP_EOL); $x = "What do you think?"; fwrite($fp, $x); echo "Now the content of file after appending is:
"; rewind($fp); while(!feof($fp)) < $line = fgets($fp); echo $line; echo "
"; > fclose($fp); > else echo "Unable to open the file
"; ?>
The output of the above PHP example is shown in the following snapshot:
Note: The feof() function checks whether the file pointer has been reached at the end of the file.
Note: The fgets() function is used to read the content of a file, line-by-line.
Note: The rewind() function moves the file pointer to the beginning of the file.
Liked this article? Share it!