Home >Backend Development >PHP Tutorial >How to Prepend Data to the Beginning of a File in PHP?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-07 18:45:031083browse

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

Appending Data to the Beginning of a File in PHP

When writing data to a file in PHP, it is typically appended to the end of the existing file. However, there may be scenarios where you want to insert data at the beginning of the file.

Problem Overview

  • Writing data directly to a file overwrites any existing content.
  • Rewinding the file with rewind($handle) may overwrite content if the input data is larger than the file size.

Solution

To prepend data to the beginning of a file, follow these steps:

  1. Read the existing file contents into a variable using file_get_contents().
  2. Concatenate the data you want to prepend before the existing file contents.
  3. Write the combined data back to the file using file_put_contents().

Example:

<code class="php">$prepend = 'prepend me please';

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $prepend . $fileContents);</code>

This solution combines the input data with the existing file contents and writes them to the beginning of the file, ensuring that any previous data is preserved.

The above is the detailed content of How to Prepend 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