首先创建一个表单,命名为 index.html
<!DOCTYPE html>
<head>
<title>表单</title>
</head>
<body>
<form action="form.php" method="post">
<p>text: <input type="text" name="text" /></p>
<input type="submit" value="Submit" />
</form>
</body>
然后创建一个 php 文件,命名为 form.php
<?php
$file = 'text.txt';
$content = file_get_contents($file);
?>
<?php
echo file_put_contents("text.txt","$content");
?>
<?php
$file = 'text.txt';
$t = $_POST["text"];
$text = "\n$t";
// 向文件追加写入内容
// 使用 FILE_APPEND 标记,可以在文件末尾追加内容
// LOCK_EX 标记可以防止多人同时写入
file_put_contents($file, $text, FILE_APPEND | LOCK_EX);
?>
最后再创建一个 txt 文件,命名为 text.txt
打开表单,输入任意内容并提交,内容就会被保存到 text.txt 文件中
思路分析:
使用 POST 方式提交表单数据给 form.php
form.php 收集表单数据并写入文件