首页 > 解决方案 > 如何从外部 json 文件中读取登录详细信息?

问题描述

我很难从外部 json 文件中读取用户名和密码。我想将用户输入的用户名和密码与 json 用户名和密码匹配。有人可以帮我吗?谢谢

我的.json

[
  {
    "username":"user@email.com",
    "password":"123456"
  },
  {
    "username":"newuser@email.com",
    "password":"98765"
  }
]

php代码

$username = $_POST['username'];
        $password = $_POST['password'];
        $JSON = file_get_contents("my.json");
        $jsonIterator = new RecursiveIteratorIterator(
                        new RecursiveArrayIterator(json_decode($JSON, TRUE)),
                        RecursiveIteratorIterator::SELF_FIRST);

       foreach ($jsonIterator as $key => $val) {
    
        if($val==$username &&  $val == $password) {
            print "found";
            $_SESSION['signin'] = $username
        
        }

标签: phpjson

解决方案


首先,以明文形式存储密码是非常不安全的,密码应该是散列的。此外,包含用户名/密码组合的文件(无论是数据库还是 JSON)都应该受到密码保护。

通常,您将通过密码登录到mysql数据库,这会在您的 Web 应用程序之外创建一个额外的安全层。另一种但可能不太安全的方法是加密和解密您的 json 文件(我只浏览了该链接的代码,我不保证他们的方法是安全的)。这适用于小型数据集,但不适用于大型数据集。

说了这么多,如果你有一个bad-security.json文件:

$file = __DIR__.'/bad-security.json';
$encryptedContent = file_get_contents($file);
$content = decrypt($encryptedContent, ...); //you'd have to write the decrypt function
$usernamePasswords = json_decode($content,true);

$passwordInput = $_POST['password'];
$emailInput = $_POST['email'];

foreach ($usernamePasswords as $email=>$passwordHash) {
    if ($email!==$emailInput)continue;
    if (password_verify($passwordInput, $passwordHash){
        $_SESSION['userEmail'] = $email;
    }
}

存储密码将类似于:

$usernamePasswords = json_decode($content,true);
$email = $_POST['email'];
$newPassword = $_POST['newPassword'];
$confirm = $_POST['confirmNewPassword'];
if ($confirm!==$newPassword)return;// or throw an exception or whatever
$passwordHash = password_hash($newPassword, PASSWORD_BCRYPT, $options);
//put the $passwordHash into the $usernamePasswords array
$json = json_encode($usernamePasswords);
$output = encrypt($json);
file_put_contents(__DIR__.'/bad-security.json', $output);


推荐阅读