How to Write Data to the Beginning of a File in PHP Without Overwriting Existing Content?

DDD
Release: 2024-11-07 00:30:03
Original
1063 people have browsed it

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+");
Copy after login

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);
?>
Copy after login

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:

  • file_get_contents('database.txt') reads the existing file and stores its contents in the $file_data variable.
  • You can modify the $file_data variable to add your new data at the beginning or anywhere else in the string.
  • file_put_contents('database.txt', $file_data) overwrites the original database.txt file with the new combined content from $file_data.

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!

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