Home > Article > Backend Development > 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
Solution
To prepend data to the beginning of a file, follow these steps:
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!