Table of Contents
Understanding file_put_contents() Function
最终想法
Home Backend Development PHP Tutorial PHP Tutorial: How to Append File Contents Using PHP

PHP Tutorial: How to Append File Contents Using PHP

Aug 31, 2023 pm 07:33 PM
php append file

PHP Tutorial: How to Append File Contents Using PHP

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 using implode() in order to write the data to a file.
  • flags: Control the behavior of file_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.

In some special cases, you may be appending data to a file from multiple scripts at the same time. In these cases, it is recommended to use the

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.

This is an example where

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);

?>
Copy after login

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.

One way to solve this problem is to call these functions yourself. Just call

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 a or 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 a method, 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.
Now that the file is open, we can add information to the file using the

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.
After all writing operations are completed, you can close the file handle using the

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);

?>
Copy after login
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.
Copy after login

在本例中,我们将数字 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles