Get the App
SLTechnology News&Howtos  ›  Development  › 

Can php modify the contents of the file

Shulou Source: shulou.com Published: 2022-06-03 05:17:34 09月18日 Update

This article will explain in detail whether php can modify the contents of the file. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Php can modify the contents of the file, method: 1, use the fopen () function to open the file, use the fwrite () function to write data in the open file can modify the file. 2. Use the file_put_contents () function directly to modify the file by emptying the file and re-adding data or adding data at the end of the file.

Operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

1. Use the fwrite () function

The fwrite ($handle, $string, $length) function writes a string to a file. The fwrite () function writes the contents of $string to the file pointer $handle. If $length is specified, writing stops when $length bytes have been written or $string has been written. If the function executes successfully, it returns the number of bytes written; if the function fails, it returns FALSE.

Example 1: clear the file and re-add data

Example 2: add data at the end of the file

2. Use the file_put_contents () function

The file_put_contents ($filename,$data,$mode,$context) function can write a string to a file, accepting two required parameters, $filename (the file to be opened) and $data (the content to be inserted, which can be a string, an one-dimensional array, or a resource, etc.), and two omitted parameters $mode and $context (the environment of the file handle).

Where the $mode parameter is used to open / write a file (that is, file mode), and has three values:

FILE_USE_INCLUDE_PATH: default value, which is used to overwrite the original data.

FILE_APPEND: if the file $filename already exists, append the data instead of overwriting it.

LOCK_EX: acquire an exclusive lock when writing.

Example 1: clear the file and re-add data

Example 2: add data at the end of the file

This is the end of the article on "can php modify the contents of the file". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Files functions data content examples parameters characters strings articles bytes more environment good practical successful three two handles done pointers Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Apple Shulou Technology macOS MariaDB