Php登录存储密码在txt [英] Php login store passwords in 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.
- 获取用户名和密码。
- 将原始用户列表读入数组。
- 附加新的用户名和密码。
- 将其转换为JSON。
- 将其保存在文件中。
- Get the username and password.
- Read the original list of users into an array.
- Append the new username and password.
- Convert it into JSON.
- 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屋!