How to Prepend Data to a File in PHP?

DDD
Release: 2024-11-07 22:12:03
Original
910 people have browsed it

How to Prepend Data to a File in PHP?

File Append vs. Prepend in PHP

Appending data to the end of a file in PHP is straightforward using the "a" (append) mode. However, writing to the beginning of a file requires a more nuanced approach.

In the scenario described, the "r " mode (read-write) allows the addition of data, but overwrites previous contents. To avoid this limitation, a more intricate technique is required.

Solution Using file_put_contents()

The solution involves using file_put_contents() in conjunction with file_get_contents(). This method reads the existing file contents, prepends the desired data, and then overwrites the file with the combined string:

$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
Copy after login

This approach effectively inserts the new data at the beginning of the file, while preserving the existing content.

Example

In the provided HTML file, the following code can be added after the "fclose($datab);" line:

$file_data = $form . file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
Copy after login

This modification will ensure that new user submissions are added to the top of the "database.txt" file.

The above is the detailed content of How to Prepend Data to a File in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!