Php 如何将HTML表单中输入的字符串保存到文本文件
我有一个非常基本的PHP文件。我想有两个文本框供用户输入,还有一个提交按钮。用户将输入他们的名字和姓氏,然后我想用从field1和field2输入的数据附加或创建一个TXT文件 可能我走错了方向。我将发布我一直在修补的两种方法Php 如何将HTML表单中输入的字符串保存到文本文件,php,html,string,Php,Html,String,我有一个非常基本的PHP文件。我想有两个文本框供用户输入,还有一个提交按钮。用户将输入他们的名字和姓氏,然后我想用从field1和field2输入的数据附加或创建一个TXT文件 可能我走错了方向。我将发布我一直在修补的两种方法 <html> <head> <title>Field1 & 2</title> </head> <body> <form> What is your name?&
<html>
<head>
<title>Field1 & 2</title>
</head>
<body>
<form>
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
<?php
$txt= $_POST['field1'].' - '.$_POST['field2'];
$var_str3 = var_export($txt, true); //is this necessary?
$var3 = "$var_str3"; //is this necessary?
file_put_contents('fields.txt', $var3.PHP_EOL, FILE_APPEND);
?>
</body>
</html>
字段1和字段2
你叫什么名字?
我不知道如何将field1和field2中的数据转换成字符串变量
我还乱用这个php而不是上面列出的部分
<?php
$txt= "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
让我们从
if
语句之所以存在,是因为第一次加载脚本action\u page.php
时,它的目的只是显示表单,不接收任何POST数据
当用户提交表单时,脚本将接收数据并存储到文件中
脚本还将(使用这种方法)再次显示一个空表单,准备提交另一个条目
您可以重新安排内容,以便拥有两个网页:一个只包含表单,另一个包含“谢谢”消息和数据处理php脚本。您应该了解和php
在代码中,必须使用表单HTTP方法。表单数据必须发送到PHP文件进行处理
在这段代码中我使用HTTP PSOT方法,你也可以使用GET方法,结果将是一样的。这两种方法用于收集表单数据。php文件名为“action.php”
index.html
<html>
<head>
<title>Field 1 & 2</title>
</head>
<body>
<form action="action.php" method="post">
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
场1和场2
你叫什么名字?
action.php
<?php
$path = 'data.txt';
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
您的表单没有
方法
属性,这意味着将使用默认方法GET。如果要在PHP中访问POST参数,必须将method=“POST”
添加到表单元素中。
<html>
<head>
<title>Field 1 & 2</title>
</head>
<body>
<form action="action.php" method="post">
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
$path = 'data.txt';
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>