Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP undefined index on array lookup

Tags:

arrays

php

I have a list of IP's in a text file. I want get the user's IP and then count in the array to see if they have made more than 2 requests.

However I am getting

Undefined index: xx.xxx.xxx.xx

where

xx.xxx.xxx.xx is my IP. 

(hiding for obvious reasons)

When I have more than 2 of the same IP in the txt file it returns the 'Too many lookups' but if the $value isn't found in the array it returns undefined index. I thought I had the catch with !isset but if I remove the ! it just runs the request. If I keep it as !isset it runs but then returns undefined index.

I have even tried

if(array_key_exists($value, $array_list)){

but nothing. Any ideas why?

$list = file_get_contents('ips.txt');

// convert to array
$array_list = (explode(" ",$list));

// Get user's ip
$value = $_SERVER['REMOTE_ADDR'];

if(!isset($array_list[$value])){

    $values = array_count_values($array_list); 
    $count = $values[$value];

    if ($count > 2) {
        return 'Too many lookup attempts, please try again in 24    hours click <a href="/">HERE</a> to return home';
        }

    }

    else {
        // run the ok request
    }
like image 986
ServerSideSkittles Avatar asked Jun 02 '26 16:06

ServerSideSkittles


1 Answers

It seems you're confusing array values and array keys

Explode returns an array where all the items from the string are values and the keys are just numbers starting from 0. Take this example:

$string = "foo bar baz";
$array = explode(' ', $string);
/*
 * Array now holds
 * [0] => "foo",
 * [1] => "bar",
 * [2] => "baz",
 */

In the example 0,1,2 are the keys and foo, bar, baz are the values.

So when you execute

// convert to array
$array_list = (explode(" ",$list));

Your keys are the numbers 0-n (n being however many IPs were in the list). Each key has a corresponding value, those values are the actual IPs.

So now when you run

if(!isset($array_list[$value])){

What you're telling PHP to do is to find an entry in the array with key that matches your IP. Except no keys in the array are IP addresses.

If you want to find out if a certain value exists in the array use array_search(). OR in your case, since you're running your list through array_count_values() which is going to convert your values into keys, you could do a normal isset() lookup on the $values variable after running the function.

$values = array_count_values($array_list); // Each IP is now a key of $values
if (isset($values[$value])) {
    // The IP shows up at least once
    $count = $values[$value];

    // continue with other logic here
}
else {
    // The IP is not in the list

    // continue with other logic here
}
like image 187
tbernard Avatar answered Jun 04 '26 05:06

tbernard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!