dpqvwgr74759 2015-09-15 16:11
浏览 75
已采纳

登录表单只包含php和html以及用户,并在.txt文件中传递id

so I'm trying to create a login form with only html, php and txt files (I can't use a database for this assignment). I'm new to php but i have kinda got i to work. My txt file looks like name|password for example:

Jacob|transport
Lars|griskraft

The problem i have is that it works with the last name|password combo in my txt file but not with another name and password combo before them.

Here is my code:

<?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>";
}
}

?>

Here is the html form:

<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>
  • 写回答

1条回答 默认 最新

  • dongnuo6310 2015-09-15 16:26
    关注

    You have few empty/white spaces in .txt file, in first line, that was problem, so, trim() it:

    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) will show you that there are few more invisible chars...

    Tested it, and now works fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记