使用PHP表单输入写入文件



我正在做的项目对象涉及制作不同的PHP表单来创建、写入、读取和删除文件。这(insert.php)是我的"写入"页面,并正确打开文件,但是当"fileInsert"按钮被按下时,它刷新页面并在写入或显示成功消息之前关闭打开的文件。任何帮助或建议都很感谢

<!DOCTYPE html>
<html>
<head>
<title>File Creator</title>
</head>
<body>
<h1>File Creator</h1>
<form action="" method="post">
<label for="fileName">Enter the name of the file you would like to open including the extension:</label><br />
<input type="text" name="fileName"><br />
<input type="submit" value="Open File" name="fileOpen">
</form>
</body>
<?php

if(isset($_POST['fileOpen'])) {
$fileName = $_POST['fileName'];
echo str_ireplace("None", $fileName, "<h3>Currently open: None</h3><br />");
if (is_file($fileName)) {
echo "<form action='' method='post'>";
echo "<label for='fileInput'>File is open!<br />Insert up to 40 characters:</label><br />";
echo "<input type='text' name='fileInput' maxlength='40'><br />";
echo "<input type='submit' value='Submit' name='fileInsert'><br /><br />";
echo "</form>";
if(isset($_POST['fileInsert'])) {
$fileInput = $_POST['fileInput'];
$myfile = fopen($fileName, "w");
fwrite($myfile, $fileInput);
fclose($myfile);
echo "Done! <br />";

}
}
else {
echo "File does not exist. <br /><br />";
echo "<a href='start.php'><button>Return to Homepage</button></a>";
}

}
else {
echo "<h3>Currently open: None</h3><br />";
}
?>
</html>```

每次表单被发送到同一页面或任何其他…$_POST中只有最近的post数据。

很简单…由于您在同一页面中提交了另一个表单…第二次提交再次重新加载页面…但现在……$_POST['fileOpen']中没有什么要处理的,因为第二篇文章只包含第二篇文章的数据,所以这里是一个固定的版本:

<!DOCTYPE html>
<html>
<head>
<title>File Creator</title>
</head>
<body>
<h1>File Creator</h1>
<form action="" method="post">
<label for="fileName">Enter the name of the file you would like to open including the extension:</label><br />
<input type="text" name="fileName"><br />
<input type="submit" value="Open File" name="fileOpen">
</form>
</body>
<?php
if(isset($_POST['fileInsert'])) {
$fileInput = $_POST['fileInput'];
$myfile = fopen($_POST['fileName'], "w");
fwrite($myfile, $fileInput);
fclose($myfile);
echo "Done! <br />";
}
if(isset($_POST['fileOpen'])) {
$fileName = $_POST['fileName'];
echo str_ireplace("None", $fileName, "<h3>Currently open: None</h3><br />");
if (is_file($fileName)) {
echo "<form action='' method='post'>";
echo "<label for='fileInput'>File is open!<br />Insert up to 40 characters:</label><br />";
echo "<input type='text' name='fileInput' maxlength='40'><br />";
echo "<input type='hidden' name='fileName' value='$fileName' >";
echo "<input type='submit' value='Submit' name='fileInsert'><br /><br />";
echo "</form>";

}
else {
echo "File does not exist. <br /><br />";
echo "<a href='start.php'><button>Return to Homepage</button></a>";
}
}
else {
echo "<h3>Currently open: None</h3><br />";
}
?>
</html>

我把$_POST['fileInsert']放在$_POST['fileOpen']外面,因为当我们得到这个时,我们没有得到那个,我在里面添加了一个隐藏的输入字段我在$_POST['fileInsert']的if中使用的第二种名为fileInput的形式,我需要知道自第一篇文章以来也丢失的文件名!

此方法还将打印"当前打开:none"在完成后的最后!

顺便说一句:这会覆盖你的文件!使用'a'代替'w'来添加到文件中。

最新更新