<?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!";
}
?>
如果你想存储用户,那么你只需要做相反的事情。
获取用户名和密码。
将原始用户列表读入数组。
附加新的用户名和密码。
将其转换为 JSON。
将其保存在文件内。
最终代码:
<?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);
?>