phpjsonfile-get-contentsarray-key-exists

PHP array_key_exists not working correctly


I have a php script that is supposed to assign virtual names to ip addresses.

<?php
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$read = file_get_contents("vnames.json");
$json = json_decode($read);
var_dump($_SERVER["REMOTE_ADDR"]);
if(!array_key_exists($_SERVER["REMOTE_ADDR"], $json)){
    $json[$_SERVER["REMOTE_ADDR"]] = generateRandomString();
    $read = json_encode($json);
    echo "This if statement is true!";
    file_put_contents("vnames.json", $read);
}
?>

Inside names.json, there are is only a pair of empty brackets.

So, I've figured out that !array_key_exists($_SERVER["REMOTE_ADDR"], $json) is false. But, I'm sure that names.json does not contain my IP address. I've assumed that this is is what's being evaluated:

<?php
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
$read = file_get_contents("vnames.json");//blank
$json = json_decode($read);//null
var_dump($_SERVER["REMOTE_ADDR"]);//My ip
if(!array_key_exists($_SERVER["REMOTE_ADDR"], $json)/*false*/){
    $json[$_SERVER["REMOTE_ADDR"]] = generateRandomString();
    $read = json_encode($json);
    echo "This if statement is true!";
    file_put_contents("vnames.json", $read);
}
?>

But in that case, file_get_contents is not working correctly. Please help!


Solution

  • array_key_exists is only for arrays, while the $json variable contains an object.

    Either change $json to be an array or use property_exists for the object.

    Example to transform $json into an array

    $json = json_decode($read, true);