Home > Article > Backend Development > How to Write Data to the Beginning of a File in PHP Without Overwriting Existing Content?
Writing to the Beginning of a File in PHP
In your program, you aim to write data to the beginning of a file, but "a"/append only adds to the end. To accomplish this, you seek an alternative to "r " that doesn't overwrite existing content.
Let's break down your code:
$datab = fopen('database.txt', "r+");
This line opens the file database.txt with read-plus ( ) permissions, allowing you to read and write. However, writing will overwrite any previous data.
To solve this issue, consider the following method:
<?php $file_data = "New data to add at the beginning\n"; $file_data .= file_get_contents('database.txt'); file_put_contents('database.txt', $file_data); ?>
This code first retrieves the existing contents of database.txt, appends your new data, and then overwrites the file with the combined content, effectively writing to the beginning. Here's how it works:
This method allows you to write data to the beginning of a file without losing the existing data.
The above is the detailed content of How to Write Data to the Beginning of a File in PHP Without Overwriting Existing Content?. For more information, please follow other related articles on the PHP Chinese website!