Writing to the Beginning of a File in PHP
Writing data to a file's beginning can be slightly tricky in PHP. The "a" mode (append) only allows you to add content to the end of a file. "r " mode, while allowing read and write access, overwrites existing data.
In your case, you've used "r " which has this behavior:
$datab = fopen('database.txt', "r+");
Solution: Using File Operations
Here's a quick and efficient solution:
Read the existing contents of the file:
$current_data = file_get_contents('database.txt');
Concatenate the new data with the existing data:
$new_data = "Your new data\n" . $current_data;
Rewrite the entire file with the new data:
file_put_contents('database.txt', $new_data);
This technique ensures that your new data is written at the beginning of the file, while preserving the previous contents.
Here's a code snippet that demonstrates this solution:
<?php $new_data = "Your new data\n"; $current_data = file_get_contents('database.txt'); $new_data .= $current_data; file_put_contents('database.txt', $new_data); ?>
The above is the detailed content of How to Write Data to the Beginning of a File in PHP?. For more information, please follow other related articles on the PHP Chinese website!