PHP writes or appends data to a file_PHP Tutorial
PHP writes or appends data to files
There are two ways for PHP to write or append data to files, one is fopen and the other is file_put_contents. This article is brief Let me introduce the specific usage of the two methods. Friends in need can take a look.
(1)fopen
The fopen() function opens a file or URL. If the opening fails, this function returns FALSE.
Syntax: fopen(filename,mode,include_path,context)
Parameter Description
filename Required. Specifies the file or URL to open.
mode Required. Specifies the type of access required to this file/stream. Possible values are shown in the table below.
include_path is optional. If you also need to retrieve files in include_path, you can set this parameter to 1 or TRUE.
context Optional. Specifies the environment for a file handle. Context is a set of options that can modify the behavior of the stream.
Possible values for the mode parameter
mode | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
"r" | Open in read-only mode and point the file pointer to the file header. | ||||||||||||||||||
"r " | Open in read-write mode and point the file pointer to the file header. | ||||||||||||||||||
"w" | Open in writing mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. | ||||||||||||||||||
"w " | Open in read-write mode, point the file pointer to the file header and truncate the file size to zero. If the file does not exist, try to create it. | ||||||||||||||||||
"a" | Open in writing mode and point the file pointer to the end of the file. If the file does not exist, try to create it. | ||||||||||||||||||
"a " | Open in read-write mode and point the file pointer to the end of the file. If the file does not exist, try to create it. | ||||||||||||||||||
"x" |
|
||||||||||||||||||
"x " | Create and open for reading and writing, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE and generates an E_WARNING level error message. If the file does not exist, try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flag to the underlying open(2) system call. This option is supported by PHP 4.3.2 and later versions and can only be used for local files. |
Write content in append form
<?php $fp=fopen('test.txt','a');
(2) file_put_contents
The file_put_contents() function is used to write a string into a file. It returns the number of bytes of data written into the file successfully, and returns FALSE on failure.
Syntax: int file_put_contents(string filename,string data[,int flags[,resource context]])
Parameter Description
filename The name of the file to write data to
data The data to be written. The type can be string, array (but not multi-dimensional array), or stream resource
flags optional, specifies how to open/write the file. Possible values:
FILE_USE_INCLUDE_PATH: Check the built-in path for a copy of filename
FILE_APPEND: Write data by appending to the end of the file
LOCK_EX: Lock the file
context Optional, Context is a set of options through which text attributes can be modified
For example:
<?php echo file_put_contents("test.txt","www.phpernote.com"); //输出:17
Write content in append form
When the flags parameter value is set to FILE_APPEND, it means writing new data by appending content after the existing file content, for example:
<?php file_put_contents("test.txt","www.phpernote.com",FILE_APPEND);
Tips
The behavior of file_put_contents() is actually equivalent to calling the fopen(), fwrite() and fclose() functions in sequence.
If the file does not exist, create the file, which is equivalent to the fopen() function behavior.
If the file exists, the contents of the file will be cleared by default. You can set the flags parameter value to FILE_APPEND to avoid this.
The file_put_contents function is safe for use with binary objects.
Articles you may be interested in
- The safest and most realistic solution for PHP to determine the type of uploaded files
- php gets every file within a certain period of time Month method, returns an array composed of these months
- php program to get all files in a directory and save the results to an array
- Use PHP's GZip compression function to compress website JS and CSS files Compression accelerates website access speed
- PHP analyzes the file header information to determine the type of uploaded file
- Right-click the xp folder to add a new window to open the folder
- MySQL imports and Example of exporting .sql file backup data operation
- Solution to PHP failure to upload large files

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

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.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
