我有一个应该为 IP 地址分配虚拟名称的 php 脚本。
<?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);
}
?>
在 names.json 中,只有一对空括号。
所以,我发现这!array_key_exists($_SERVER["REMOTE_ADDR"], $json)
是错误的。但是,我确定 names.json 不包含我的 IP 地址。我假设这是正在评估的内容:
<?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);
}
?>
但在这种情况下,file_get_contents 无法正常工作。请帮忙!