简体   繁体   中英

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM