Php Append To File

php append to file
// LOCK_EX will prevent anyone else writing to the file at the same time
// PHP_EOL will add linebreak after each line
$txt = "data-to-add";
$myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);

// Second option is this
$myfile = fopen("logs.txt", "a") or die("Unable to open file!");
$txt = "user id date";
fwrite($myfile, "\n". $txt);
php save array to file
$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true
appending txt file from php
$log_content="This line is logged on 2020-08-14 09:55:00";
$myfile = fopen("log.txt", "a") or die("Unable to open file!");
fwrite($myfile, $log_content);

Leave a Comment