使用php验证给定用户名是否已存在于txt文件中
我有一个任务,需要创建一个注册页面,并验证txt文件中是否存在用户。我在网上找到了一些答案,并尝试应用它们,但似乎对我不起作用。除了他需要核实的部分外,一切都正常。 这是我的代码:这是我的代码使用php验证给定用户名是否已存在于txt文件中,php,html,web,Php,Html,Web,我有一个任务,需要创建一个注册页面,并验证txt文件中是否存在用户。我在网上找到了一些答案,并尝试应用它们,但似乎对我不起作用。除了他需要核实的部分外,一切都正常。 这是我的代码:这是我的代码 <?php if($_POST['formSubmit'] == "Submit") { $errorMessage =""; $link_Create = "CreateAnAccount.php"; $Username = $_POST['userName'];
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage ="";
$link_Create = "CreateAnAccount.php";
$Username = $_POST['userName'];
$password = $_POST['Password'];
if(empty($_POST['userName']))
{
echo "<li>You forget to enter a UserName</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(empty($_POST['Password']))
{
echo "<li>You forget to enter a Password</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{4,24}$/', $password))
{
echo "<li>Your Password input was wrong, please notice Paswword most be at least 4 characters long, have at least one letter and at least one digit. </li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(empty($errorMessage)){
$userlist = fopen("login.txt","r");
$success = true;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}
fclose($userlist);
if ($success==true) {
$writer = fopen("login.txt", "a") or die("Unable to open file.");
fwrite($writer,$Username."|");
fwrite($writer,$password."\n");
fclose($writer);
echo "<br>You have been logged in. <br>";
header("Location:PopUp.html");
exit;
}
else {
echo "<li>This User Name already exist!</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
}
}
?>
让我知道是否有我的html代码的需要,但我不认为这对这个问题有任何影响。
非常感谢您的帮助。您在迭代返回函数的资源时遇到问题 尝试将其替换为遍历userlist文件的每一行:
$file = new \SplFileObject("login.txt");
// Loop until we reach the end of the file
while (!$file->eof()) {
$user = $file->fgets();
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}
你现在的输出是多少?您是否收到任何错误?您从未实际读取该文件。您只需打开它:
$userlist=fopen(“login.txt”,“r”)代码>fopen()
不读取它打开的文件的内容。您确实应该开始阅读所使用函数的文档。您应该验证$\u POST['userName']
。如果名称包含您的分隔符(|
),它将在将来破坏您的解析器。我会用一个DB来做这个。您可以使用文件获取内容
然后在
上使用分解
,然后迭代名称。。或者只需在数组中使用,
如果您不需要对它们做任何事情,那么非常感谢您的帮助,我在您的代码中添加的唯一内容是:$success=true;就在while循环之前。
$file = new \SplFileObject("login.txt");
// Loop until we reach the end of the file
while (!$file->eof()) {
$user = $file->fgets();
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}