In PHP if you write to a file it will write end of that existing file.
How do we prepend a file to write in the beginning of that file?
I have tried rewind($handle)
function but seems overwriting if current content is larger than existing.
Any Ideas?
You cannot insert content at the beginning of a file. The only thing you can do is either replace existing content or append bytes after the current end of file.
If you want to add a line at the beginning of a file, you need to add \n at the end of the string in the best solution above.
Add Text to Beginning of File Using echo and cat Commands Then, we simply output the variable and redirect it to the same file. As you can see above, the new text was added on a new line at the beginning of the file. To add the text at the beginning of the existing first line, use the -n argument of echo.
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.
<?php
$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended
$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
fwrite($handle, $cache_new);
$cache_new = $cache_old;
$cache_old = fread($handle, $len);
fseek($handle, $i * $len);
$i++;
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With