【发布时间】:2021-10-22 17:55:46
【问题描述】:
我正在做的项目的目标是制作不同的 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>```
【问题讨论】:
-
fileOpen和fileInsert不能同时设置,它们在不同时间提交的不同表单上。您要么需要一个带有文件名和输入的表单,要么需要一个两步过程,第二步打开并写入。
标签: php forms file-handling file-writing