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.
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!