检查php
上的姓名和密码的对应关系。原理如下:如果名称在文件中(在json文件中存储名称和密码),文件中的密码是否与输入的密码匹配。
$file = "../data/users.json";
$json_array = json_decode(file_get_contents($file), true);
$users = array();
if(is_array($json_array)) {
$users = $json_array;
}
if(isset($users[$name])) {
if($users[$name]["pass"] !== $password ){
http_response_code(400);
}
}
else {
$users[] = array("name" => $name, "pass" => $password, "id" => $i);
$i = 0;
foreach ($users as $key => $value) {
$users[$key]["id"] = $i;
$i++;
}
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
这里写的是文件
[
{
"name": "qwe",
"pass": "qwe",
"id": 0
}
]
当我输入已存在的名称和与之不匹配的密码时,脚本会将其写为新对。
[
{
"name": "qwe",
"pass": "qwe",
"id": 0
},
{
"name": "qwe",
"pass": "qweqwe",
"id": 1
}
]
据我了解,这是因为isset($ users [$ name])总是虚假,但我不知道如何解决它。如何修复我的姓名和密码验证?
答案 0 :(得分:1)
Phiter的评论是正确的。如果您只需要代码可以工作,那么简单地将名称作为数组的索引插入:
$users[$name] = array("name" => $name, "pass" => $password, "id" => $i);
编辑:
这是完整的代码:
$file = "../data/users.json";
$json_array = json_decode(file_get_contents($file), true);
$users = array();
if(is_array($json_array)) {
$users = $json_array;
}
if(isset($users[$name])) {
if($users[$name]["pass"] !== $password ){
http_response_code(400);
}
}
else {
$i = 0;
foreach ($users as $key => $value) {
$users[$key]["id"] = $i;
$i++;
}
$users[$name] = array("name" => $name, "pass" => $password, "id" => $i);
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}
我只是将$users[$name] = array("name" => $name, "pass" => $password, "id" => $i);
移到foreach下面的行(你想添加,不是吗?!?)并将$ name作为索引。
编辑2:
如果要保留json结构,请尝试以下方法:
<?php
$file = "users.json";
$json_array = json_decode(file_get_contents($file), true);
$users = array();
if(is_array($json_array)) {
$users = $json_array;
}
$newUser = true;
foreach($users as $user) {
if ($user["name"] == $name) {
$newUser = false;
if ($user["pass"] !== $password) {
http_response_code(400);
} else {
// GOOD PASSWORD
}
}
}
var_dump($users);
var_dump(count($users));
if ($newUser) {
$users[] = array("name" => $name, "pass" => $password, "id" => count($users) + 1);
}
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
答案 1 :(得分:0)
$file = "../data/users.json";
$json_array = json_decode(file_get_contents($file), true);
$users = array();
if(is_array($json_array)) {
$users = $json_array;
}
if(isset($users[0])) {
if($users[0]["pass"] !== $password ){
http_response_code(400);
}
}
else {
$users[] = array("name" => $name, "pass" => $password, "id" => $i);
$i = 0;
foreach ($users as $key => $value) {
$users[$key]["id"] = $i;
$i++;
}
file_put_contents($file, json_encode($users, JSON_PRETTY_PRINT));
}