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

How to Write Data to the Beginning of a File in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-07 12:59:02839browse

How to Write Data to the Beginning of a File in PHP?

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:

  1. Read the existing contents of the file:

    $current_data = file_get_contents('database.txt');
  2. Concatenate the new data with the existing data:

    $new_data = "Your new data\n" . $current_data;
  3. 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!

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