且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Php登录存储密码在txt

更新时间:2023-12-03 20:18:22

的事物,并将其称为数组。所以,首先准备文件。 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);
?>