Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append at the beginning of the file in PHP [duplicate]

Tags:

php

Hi I want to append a row at the beginning of the file using php.

Lets say for example the file is containing the following contnet:

    Hello Stack Overflow, you are really helping me a lot.

And now i Want to add a row on top of the repvious one like this:

    www.stackoverflow.com
    Hello Stack Overflow, you are really helping me a lot.

This is the code that I am having at the moment in a script.

    $fp = fopen($file, 'a+') or die("can't open file");
    $theOldData = fread($fp, filesize($file));
    fclose($fp);

    $fp = fopen($file, 'w+') or die("can't open file");
    $toBeWriteToFile = $insertNewRow.$theOldData;
    fwrite($fp, $toBeWriteToFile);
    fclose($fp);

I want some optimal solution for it, as I am using it in a php script. Here are some solutions i found on here: Need to write at beginning of file with PHP

which says the following to append at the beginning:

    <?php
    $file_data = "Stuff you want to add\n";
    $file_data .= file_get_contents('database.txt');
    file_put_contents('database.txt', $file_data);
    ?>

And other one here: Using php, how to insert text without overwriting to the beginning of a text file

says the following:

    $old_content = file_get_contents($file);
    fwrite($file, $new_content."\n".$old_content);

So my final question is, which is the best method to use (I mean optimal) among all the above methods. Is there any better possibly than above?

Looking for your thoughts on this!!!.

like image 627
Som Avatar asked Dec 27 '22 02:12

Som


1 Answers

function file_prepend ($string, $filename) {

  $fileContent = file_get_contents ($filename);

  file_put_contents ($filename, $string . "\n" . $fileContent);
}

usage :

file_prepend("couldn't connect to the database", 'database.logs');
like image 179
vdegenne Avatar answered Jan 06 '23 06:01

vdegenne