1

I want to Add new data at the starting of my text file. Dats is coming dynamically.

Below is the code i have try so far :

if(isset($_POST["posten"])){
    $naam = $_POST['naam']."ø";
    $achternaam = $_POST['achternaam']."ø";
    $email = $_POST['email']."ø";
    $bericht = $_POST['bericht']."\n";
    $infile = fopen("berichten.txt","a");
    if (flock($infile,LOCK_EX)){            
        fwrite($infile, $naam);
        fwrite($infile, $achternaam);
        fwrite($infile, $email);
        fwrite($infile, $bericht);
        flock($infile,LOCK_UN);
    }       
    fclose($infile);
}
Manthan Dave
  • 2,137
  • 2
  • 17
  • 31
jelle woord
  • 193
  • 2
  • 16
  • POST has always the same structure? Or you just want to log incoming POST? Am I assuming right that you want to add new data in begining of file without even touching rest of the file? – Konrad Gałęzowski Dec 07 '16 at 10:43
  • i need the most recent data on top of the file – jelle woord Dec 07 '16 at 10:45
  • 1
    I guess you can use most rated answer from this http://stackoverflow.com/questions/1760525/need-to-write-at-beginning-of-file-with-php with LOCK_EX flag for file_put_contents. And if you want to log whole POST no matter what it's structure is, just use $dataToWrite = implode("ø", $_POST)."\n"; – Konrad Gałęzowski Dec 07 '16 at 10:47
  • 1
    Also if you're planning to parse stored data back to php, maybe better way would be to serialize your data - see http://stackoverflow.com/questions/3487595/storing-post-values-in-an-array-to-save-them-to-text-file – Konrad Gałęzowski Dec 07 '16 at 10:56

1 Answers1

0

this works for me

if(isset($_POST["posten"])){
$naam = $_POST['naam']."ø";
$achternaam = $_POST['achternaam']."ø";
$email = $_POST['email']."ø";
$bericht = $_POST['bericht']."\n";
$file_data = "$naam"."$achternaam"."$email"."$bericht";
$file_data .= file_get_contents('berichten.txt');
file_put_contents('berichten.txt', $file_data);
}
jelle woord
  • 193
  • 2
  • 16