Search code examples
phpserializationfwritefile-put-contents

PHP - Everytime I save to file the old data gets overwritten


$testarray['player1'] = $player1Plays;
$testarray['player2'] = $player2Plays;
$testarray['result'] = $result;

print_r ($testarray);

$yoyo = serialize ($testarray);

$file = 'prevdata.dat';
fopen ($file, 'w');
file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);

I'm making a small rock, paper, scissors game for class and need to save each move and results to a file. This is what I have so far and it works to serialize the data and save it to the file, but every time I play the game again it writes over the data currently in the file (I thought 'FILE_APPEND' was supposed to add on). The full code is provided here https://eval.in/624620


Solution

  • Change

    $file = 'prevdata.dat';
    fopen ($file, 'w');
    file_put_contents($file, trim($yoyo) . PHP_EOL, FILE_APPEND);
    

    to either

    $fp = fopen('prevdata.dat', 'a'); fwrite($fp, trim($yoyo));
    

    or

    file_put_contents('prevdata.dat', trim($yoyo), FILE_APPEND);