When people create a website, data is usually stored in a database. However, sometimes we need to store data in a file so that it is easier for people to read or modify it later.
PHP comes with many functions for reading and writing data from files. We can also use some of them to append data to files. In this tutorial, you will learn two different ways to append data to a file using PHP.
Understanding file_put_contents()
Function
The file_put_contents() function is one of the simplest ways to write data to a file using PHP. It accepts four different parameters to determine its behavior. The parameters are:
-
filename
: The path to the file location where we want to write data. -
data
: Specify the data to be written to the file. It is usually a string, but you can also specify an array or stream resource. This function will automatically implode the contents of a one-dimensional array usingimplode()
in order to write the data to a file. -
flags
: Control the behavior offile_put_contents()
. You can set three different flags here, either individually or in combination with other flags. Different flags can be combined using the|
operator. -
context
: Only useful if you provide additional data to PHP when you read or access content in the stream.
Append data to a PHP file using file_put_contents()
file_put_contents() The default behavior of the function is to overwrite the contents of the given file with any new data you supply. This is not advisable when you want to keep the old data and add some new data. In this case, you can use the
FILE_APPEND flag to let PHP know that it should append the data to the end of what was originally present in the file.
LOCK_EX flag to obtain an exclusive lock on the file. This helps prevent data corruption or some other unexpected behavior. When you use this flag, other scripts will wait for the current process to finish writing to the file before appending their own data.
file_put_contents() is used to append some text to an existing file.
<?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 write some strings into a file called
canada.txt which contains information about Canada. Both strings are appended to the end of the file one after the other.
Remember that this function will create a file if it does not exist yet. However, it does not create a directory that does not exist. So it's probably a good idea to check if the file exists before starting to write to it.Use
fwrite() to write data to a PHP file
Writing data to a PHP file using the file_put_contents() function is similar to calling
fopen(),
fwrite() and
fclose( in sequence ). This means that performing multiple writes to the same file can be inefficient since we are constantly opening and closing the file again and again.
fopen() at the beginning of the write operation. Afterwards, use the
fwrite() function to write the contents to the file multiple times. Finally, you can simply call
fclose() to close the file handle. Let us now discuss each step in detail.
fopen() The function accepts four different parameters that you can use to tell PHP how the file should be opened.
- filename
: The name of the file you want to open.
- mode
: The mode for opening the file can be specified with one or two characters. We want to open this file and add some text to it. To append, set the pattern using the characters
aor
a. This places the file pointer at the end of the file. PHP will also try to create the file if it does not exist. When you open a file using the
amethod, you can also read the file content.
- use_include_path
: Instructs PHP to also look for files in the specified include path. Default is false.
- context
: Only useful if you provide additional data to PHP when you read or access content in the stream.
fwrite() function.
fwrite() requires three parameters:
- resource
: This is the resource handle we created previously using
fopen().
- string
: Text to append to the file.
- length
: Optional, used to set the maximum number of bytes that should be written to the file.
fclose() function.
这里是一个示例,向您展示如何使用 fopen()
、fwrite()
和 fclose()
将数据附加到文件。
<?php //open the file $square_file = fopen("squares.txt", "a+"); //write 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); } //read the first line of the file and echo fseek($square_file, 0); echo fgets($square_file); //close the file fclose($square_file); ?>square.txt的内容
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.
在本例中,我们将数字 1 到 10 的平方写入名为 square.txt 的文件中。我们在 a+
模式下使用 fopen()
函数打开它,这意味着我们还可以从文件中读取内容以及附加我们自己的内容。每次 for 循环迭代时,都会将包含 $i
及其平方的当前值的新行附加到我们的文件中。
有一些函数,例如 fread()
和 fgets()
,您可以使用它们来读取文件中写入的内容。但是,您通常需要使用 fseek()
将文件指针放置在所需位置以按预期读取数据。循环结束后,我们转到文件的开头并使用 fgets()
读取其第一行。
最后,我们通过调用函数 fclose()
关闭文件句柄。
最终想法
在本教程中,我们学习了使用 PHP 将数据附加到文件的两种不同方法。使用 file_put_contents()
函数可以更方便地将数据写入文件。但是,当您必须对一个文件执行多次写入操作时,使用 fwrite()
会更有效。使用 fopen()
打开文件来附加数据还可以让您选择通过将文件指针移动到所需位置来读取其内容。
The above is the detailed content of PHP Tutorial: How to Append File Contents Using PHP. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.