In PHP, writing to an existing file appends data to the end of the file. If you wish to prepend content, where the new data appears at the beginning of the file, follow these steps:
1. Retrieve Current File Contents:
Use the file_get_contents() function to read the existing file contents into a variable.
$fileContents = file_get_contents($file);
2. Create Prepend String:
Define the string you wish to prepend to the file.
$prepend = 'prepend me please';
3. Concatenate Strings:
Combine the prepend string with the current file contents using string concatenation.
$newContents = $prepend . $fileContents;
4. Overwrite File:
Open the file for writing and truncate its contents. Then, write the combined string to the beginning of the file.
file_put_contents($file, $newContents);
This approach ensures that the new content is written at the beginning of the file, effectively prepending it.
The above is the detailed content of How can I prepend content to a file in PHP?. For more information, please follow other related articles on the PHP Chinese website!