Login checks user and passowrd from json file(php). How to read file from json file

Viewed 56

I have that problem that just throws me a mistake to try again, it doesn't check json file.

here is my php code:

<?php

if (isset($_SERVER["PHP_AUTH_USER"]) && isset($_SERVER["PHP_AUTH_PW"])) {
$json = file_get_contents("user-data.json");
$json_data = json_decode($json, true);
$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key => $value) {
    if ($value['PHP_AUTH_USER'] == $user && $value['PHP_AUTH_PW'] == $pw) {
        $flag = true;
        **echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
        break;
    }
if($flag){
header('location: index.php');
} else {
  http_response_code(401);
  header("WWW-Authenticate: Basic realm=\"SECRET\"");
  echo "<p>Try again.</p>\n";
  }
 }
}

here is my .json file

{
"user":"admin",
"password":"admin"
},
{
"user":"login",
"password":"login"
}

it just throws me a mistake to try again, it doesn't check json file.

1 Answers

Please add a pair of square brackets to enclose your "json data" , which contains an array of data (multiple username and password pairs).

Hence, the following will be one of a ways to get the username and password from the json data (I commented out the file_get_contents part and use a string to store it so that it is more straight forward)

<?php
//$json = file_get_contents("./user-data.json");

$json='[{
"user":"admin",
"password":"admin"
},
{
"user":"login",
"password":"login"
},
{
"user":"stackoverflow",
"password":"goodpassword"
}
]';

$json_data = json_decode($json, true);

foreach ($json_data as $key=>$getdata) {
   echo $getdata["user"] . "-" . $getdata["password"];
   echo "<hr>";
}
    ?>

See the result in this sandbox (click execute please):

https://wtools.io/php-sandbox/b7Qv

Hence, please amend the above code to perform comparison with $_SERVER["PHP_AUTH_USER"] and $_SERVER["PHP_AUTH_PW"] to suit your case. So, change the block:

$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key => $value) {
    if ($value['PHP_AUTH_USER'] == $user && $value['PHP_AUTH_PW'] == $pw) {
        $flag = true;
        **echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
        break;
    }

to

$user = $_SERVER["PHP_AUTH_USER"];
$pw = $_SERVER["PHP_AUTH_PW"];
$flag =false;
foreach ($json_data as $key=>$getdata) {

    if ($user == $getdata["user"] && $pw == $getdata["password"]) {
        $flag = true;
        **echo "<p>Pozdrav $user, unijeli ste $pw kao zaporku.</p>\n";**
        break;
    }

}

Related