简体   繁体   English

PHP读写文本文件

[英]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: 这是代码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 文本文件以以下格式保存:0; 0

You should close the file to properly write it to disk 您应该关闭文件以将其正确写入磁盘

Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM