Home  >  Article  >  Backend Development  >  How to Write Data to the Beginning of a File in PHP Without Overwriting Existing Content?

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

DDD
DDDOriginal
2024-11-07 00:30:03988browse

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:

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

Statement:
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