登录表单只有php和html和用户和传递id在一个.txt文件


Login form with only php and html and user and pass id in a .txt file

所以我试图创建一个登录表单只有html, php和txt文件(我不能使用这个任务的数据库)。我是新的php,但我有点得到我的工作。我的txt文件看起来像name|password,例如:

Jacob|transport
Lars|griskraft

我的问题是,它的工作与姓氏|密码组合在我的txt文件,但不与另一个名称和密码组合在他们之前。

下面是我的代码:
<?php
if ($_POST) {
$userN = $_POST ['name'];
$passW = $_POST ['password'];
// Puts the whole array in a file every new line is an array
$userlist = file ( 'users.txt', FILE_SKIP_EMPTY_LINES );
// Defines a boolean success to false
$success = false;
foreach ( $userlist as $user ) {
    $user_details = explode ( '|', $user);
    //if ($user_details [0] == $userN && $user_details [1] == $passW) {
    if ((in_array($userN, $user_details) and (in_array($passW,     $user_details)))) {
        $success = true;
        echo $success . " is: ";
        break;
    }
}
if ($success) {
    echo "<br> Hi $userN you have been logged in. <br>";
} else {
    echo "<br> You have entered the wrong username or password. Please try again. <br>";
}
}
?>

下面是html表单:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <form action="" method="POST">
        Comments:
        <textarea rows="10" cols="30" name="commentContent"></textarea>
        <br /> Name: <input type="text" name="name"><br /> Password: <input
            type="password" name="password" size="15" maxlength="30" /> <br /> <input
            type="submit" value="Post!"> <br />
    </form>
    </body>
    </html>

你有几个空白/空白的。txt文件,在第一行,这是问题,所以,trim()它:

foreach ( $userlist as $user ) {
    $user_details = explode ( '|', $user);
   if (trim($user_details [0]) == $userN && trim($user_details [1]) == $passW) {
    //if ((in_array($userN, $user_details) and (in_array($passW,     $user_details)))) {
        $success = true;
        echo $success . " is: ";
        break;
    }
}

var_dump($user_details)将显示有更多的不可见字符…

测试过了,现在可以正常工作了