Php登录存储密码在txt [英] Php login store passwords in txt

查看:282
本文介绍了Php登录存储密码在txt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我知道在文本文件中存储密码不安全,但不要担心。安全不是我的目标这里,这是像那些hackme网站之一。

所以,我需要知道,我如何存储用户名和密码在一个文本文件,到目前为止我有这个数组

Now, I know that storing passwords in a text file is not secure, but don't worry. Security is not my goal here, this is like one of those hackme websites.
So, I need to know, how would I store usernames and passwords in a text file, so far I have this array

$logins = array('Example' => '123','test' => '123','simon' => '123');

和此if语句

if (isset($logins[$Username]) && $logins[$Username] == $Password){
    /* Success: Set session variables and redirect to Protected page  */
    $_SESSION['UserData']['Username']=$logins[$Username];
    header("location:index.php");
    exit;
}

我如何做到这一点,而不是将它们作为列表存储将它们存储在文本文件中,然后在文本文件上运行if语句。

How would I make it so rather than storing them as a list, I can store them in a text file, and then run the if statement, on the text file?

推荐答案

的事物,并将其称为数组。所以,首先准备文件。 passwords.json (或 passwords.txt ,请调用任何您想要的内容)的内容:

You can make a JSON kind of thing and refer it as an array. So, prepare the file first. The contents of passwords.json (or passwords.txt, call it whatever you want):

{}

现在,您需要做的是以下操作:

And now, what you need to do is the following:


  • 读取文件的内容。

  • <
  • 检查密钥是否存在用户名。

  • 验证密码。

  • Read the contents of the file.
  • Parse them into an associative array.
  • Check the keys for existence of username.
  • Verify the password.

因此,最终代码如下:

<?php
    // Read the file.
    $users = file_get_contents("passwords.json");
    // Convert into an associative array.
    $users = json_decode($users);
    // Get the input from the user.
    $username = $_POST["username"];
    $password = $_POST["password"];
    // Check the validity.
    if (array_key_exists($username, $users) && $users[$username] == $password) {
        // Valid user.
        $_SESSION["user"] = array($username, $password);
    } else {
        echo "Not Right!";
    }
?>

如果你想存储用户,那么你只需要做相反的事。

And if you wanna store the users, then you just need to do the opposite.


  1. 获取用户名和密码。

  2. 将原始用户列表读入数组。

  3. 附加新的用户名和密码。

  4. 将其转换为JSON。

  5. 将其保存在文件中。
  1. Get the username and password.
  2. Read the original list of users into an array.
  3. Append the new username and password.
  4. Convert it into JSON.
  5. Save it inside the file.

最终代码:

<?php
    // Read the file.
    $users = file_get_contents("passwords.json");
    // Convert into an associative array.
    $users = json_decode($users);
    // Get the input from the user.
    $username = $_POST["username"];
    $password = $_POST["password"];
    // Store the new one into the array.
    $users[$username] = $password;
    // Convert back to JSON.
    $users = json_encode($users);
    // Put it into the file.
    file_put_contents("passwords.json", $users);
?>

这篇关于Php登录存储密码在txt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆