Php 使用表单提交覆盖txt文件上的变量
我想做的是,当用户单击增量按钮$var时,它存储在File.txt中,变成$var+10。下面是我得到的: first.php代码:Php 使用表单提交覆盖txt文件上的变量,php,forms,file,form-submit,increment,Php,Forms,File,Form Submit,Increment,我想做的是,当用户单击增量按钮$var时,它存储在File.txt中,变成$var+10。下面是我得到的: first.php代码: <?php $myFile = "File.txt"; $fh = fopen($myFile, 'r'); $theData = fread($fh, 5); fclose($fh); ?> 以下是主页代码: <?php include 'first.php'; $var = $theData
<?php $myFile = "File.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
?>
以下是主页代码:
<?php
include 'first.php';
$var = $theData + 10;
$myFile = "File.txt";
$thetext=$_POST['sometext'];
writemyfile($myFile,$thetext,"w");
function readmyfile($thefile)
{
$myfile=fopen($thefile,"r");
$x = fread($myfile, filesize($thefile));
fclose($myfile);
return $x;
}
function writemyfile($thefilename,$data,$mode)
{
$myfile=fopen($thefilename,$mode);
fwrite($myfile,$data);
fclose($myfile);
}
?>
<html>
<head>
<title>Example of a form</title></head>
<form method="post" action="<?php echo $php_self ?>">
<input type="hidden" name="sometext" value="<?php echo $var ?>" >
<input type="submit" name="Submit" value="increment">
</form>
</html>
问题是,每次我刷新主页时,如果不单击“增量”按钮,就会显示File.txt上的值。让您的writemyfile方法进行一些错误检查,以确保其中确实存在值。如果文本为null,就像刷新没有POST值的页面时一样,那么它将以write方式打开文件,并尝试将null写入其中。每次处理mainpage.php时,您都会写入文件,即使$\u POST是空页面刷新而不发送表单。在写入该文件之前,检查$u POST是否为非空;$thetext=$_POST['sometext'];如果$_POST['sometext']=NULL{$thetext=-1;}或者{writemyfile$myFile,$thetext,w;};