我有一个简单的PHP脚本,它将表单中提交的数据保存在.txt
文件中。
问题在于重复条目(For example
当有人使用相同的名称和电子邮件多次提交表单时,我必须另外清理。
PHP Script
:
<?php
if(isset($_POST['submit'])) {
$option = $_POST['option'];
$name_field = $_POST['name'];
$lastname_field = $_POST['lastname'];
$email_field = $_POST['email'];
$terms = $_POST['terms'];
$file = "collect.txt";
$data = "$name_field; $lastname_field; $email_field; $option; $terms;\n";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
header ('index.php');
}
如果电子邮件已经提交,是否有办法过滤掉或阻止在.txt
内写入数据?
答案 0 :(得分:1)
您可以在将电子邮件插入文本文件之前搜索该电子邮件。
$data = "$name_field; $lastname_field; $email_field; $option; $terms;\n";
$fp = fopen($file, "r+") or die("Couldn't open $file for writing!");
$contents = fread($fp, filesize($file));
if (strpos($contents, $email_field) === false) {
fwrite($fp, $data) or die("Couldn't write values to file!");
}
else {
die('Email exists');
}
答案 1 :(得分:0)
为计算机添加唯一ID,例如通过cookie /会话。使用此ID将文件存储在您的计算机上。现在,如果用户重新提交表单,例如因为他们进行了更正,则覆盖旧文件。
答案 2 :(得分:0)
您可以在文件中搜索信息。要打开文件,只需使用file_get_contents()
即可。
但是,这是您不应该使用文件的原因之一,而是数据库。
答案 3 :(得分:0)
您想要检查文件内容是否包含您需要的电子邮件
$contents = fread($fp, filesize($file));
if(strpos($contents, "; $email_field;") === 0)
{
// email already in file
}else
{
// append data to file
}
你应该使用一些更复杂的正则表达式来确保电子邮件已经在文件中但是它没有作为姓氏提交,例如
答案 4 :(得分:0)
$option = $_POST['option'];
$name_field = $_POST['name'];
$lastname_field = $_POST['lastname'];
$email_field = $_POST['email'];
$terms = $_POST['terms'];
$file = "collect.txt";
$data = "$name_field; $lastname_field; $email_field; $option; $terms;\n";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
$ok = true;
while (($line = fgets($fp)) !== false) {
$arr = explode(";", $data);
if($arr[2] === $email_field) {
$ok = false;
}
}
if($ok) {
fwrite($fp, $data) or die("Couldn't write values to file!");
}
fclose($fp);
header ('index.php');
}
答案 5 :(得分:0)
您应该注意文件结构......如果我在My;wonderful;name;\n
的输入字段中输入name
怎么办?你的数据会搞砸......
由于您的数据看起来像CSV格式的文件,我认为您应该使用相关的PHP函数来处理您的文件结构:
然后你会有这样的事情:
if(isset($_POST['submit'])) {
$option = $_POST['option'];
$name_field = $_POST['name'];
$lastname_field = $_POST['lastname'];
$email_field = $_POST['email'];
$terms = $_POST['terms'];
$file = "collect.txt";
$fpr = fopen($file, "r") or die("Couldn't open $file for reading!");
while ($line = fgetcsv($fpr)) {
if ($line[2] == $email_field) {
// email already exists (give the user a message)
fclose($fpr);
header('Location: index.php');
exit();
}
}
fclose($fpr);
$data = array(
$name_field,
$lastname_field,
$email_field,
$option,
$terms
);
$fpw = fopen($file, "w") or die("Couldn't open $file for writing!");
fputcsv($fpw, $data);
fclose($fpw);
header('Location: index.php'); // note here your wrong header
}