Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-07 12:59:02
Original
933 people have browsed it

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

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');
    Copy after login
  2. Concatenate the new data with the existing data:

    $new_data = "Your new data\n" . $current_data;
    Copy after login
  3. Rewrite the entire file with the new data:

    file_put_contents('database.txt', $new_data);
    Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template