PHP 写入和读取文本文件
PHP Writing and Reading to Text File
我在我的网站上进行了投票 'poll',并使用文本文件保存结果。我基本上是在阅读现有结果,增加新结果并再次保存。
不过,好像是读取文件,然后保存文件。但是当我重新读取数据以在之后检查时,文件似乎没有正确保存......我不确定发生了什么,我的网络服务器权限应该没问题,因为我也有一个访客计数器 writes/reads 到文本文件。
代码如下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);
?>
文本文件以以下格式保存:
0;0
您应该关闭文件以将其正确写入磁盘
尝试
fputs($wfile, $insertvote);
fclose($wfile); //close the file
echo("Done.");
我在我的网站上进行了投票 'poll',并使用文本文件保存结果。我基本上是在阅读现有结果,增加新结果并再次保存。
不过,好像是读取文件,然后保存文件。但是当我重新读取数据以在之后检查时,文件似乎没有正确保存......我不确定发生了什么,我的网络服务器权限应该没问题,因为我也有一个访客计数器 writes/reads 到文本文件。
代码如下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);
?>
文本文件以以下格式保存: 0;0
您应该关闭文件以将其正确写入磁盘
尝试
fputs($wfile, $insertvote);
fclose($wfile); //close the file
echo("Done.");