Search code examples
phphtmlfilefwritevote

PHP Writing and Reading to Text File


I have a voting 'poll' on my website and to save the results it uses a text file. I am basically reading the existing results, incrementing the new results and saving it again.

However, it seems to read the file, then save the file. But when I re-read the data to check afterwards the file doesn't seemed to have saved properly... I am unsure of what's up and my web servers permissions should be OK as I have a visitor counter too that writes/reads to a text file.

Here is the code poll_vote.php:

<?php
$vote = $_REQUEST['vote'];

//open file read current votes
$contents = file("poll_result.txt");

//put content in array, split between the ;
$array = explode(";", $contents[0]);
$yes = $array[0];
$no = $array[1];

echo("Opened file and read contents. YES-" . $yes . " NO-" . $no . "<br>");

//Check if it's a yes or no vote
if ($vote == 0)
{
  $yes = $yes + 1;
  echo("Incremented yes vote, it is now" . $yes . "<br>" );
}

if ($vote == 1)
{
  $no = $no + 1;
  echo("Incremented no vote, it is now" . $no . "<br>" );
}

//insert new votes to txt file
$insertvote = $yes. ";". $no;

echo("To insert: " . $insertvote . "<br>");

$wfile = fopen('poll_result.txt', w);
fputs($wfile, $insertvote);

echo("Done.");

//////////////////////////////////////////////////

//open file read current votes
$contents = file("poll_result.txt");

//put content in array, split between the ||
$array = explode(";", $contents[0]);
$yes = $array[0];
$no = $array[1];

echo("Re-read data: " . $yes . "|" . $no);

?>

The text file is saved in the format: 0;0


Solution

  • You should close the file to properly write it to disk

    Try

    fputs($wfile, $insertvote);
    fclose($wfile); //close the file
    echo("Done.");