"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Prepend Data to a File in PHP?

How to Prepend Data to a File in PHP?

Published on 2024-11-08
Browse:163

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

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

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3