使用php验证txt文件中是否已存在给定的用户名

时间:2016-04-07 17:49:18

标签: php html web

我有一项任务,我需要创建一个注册页面并验证用户是否已经存在于txt文件中。我在网上找到了一些答案并尝试应用它们但似乎并不适合我。一切都有效,除了他需要验证的部分。 这是我的代码:这是我的代码

<?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代码,但我不认为它对此问题有任何影响。 非常感谢,我感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

对于返回fopen函数

的资源进行迭代时遇到问题
$userlist = fopen("login.txt","r");
$success = true;
foreach ($userlist as $user) {
    $user_details = explode('|', $user);
    if ($user_details[0] == $Username) {
        $success = false;
        break;
    }
}

尝试将这个迭代替换为用户列表文件的每一行:

$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;
    }
}