Liam W
Liam W

Reputation: 1163

Custom function returns true when it should return false?

I have the function below, which accepts an array of IP cidr's or single IP's, like so:

$cidrs = array("127.0.0.1","65.87.43.65/32");

Etc..

The function then checks to see if a given IP is listen in that array of IP's and CIDR's, whether it be in a CIDR or it be a single IP specified.

The issue is that if an IP doesn't contain a CIDR mask, then it will always return true - no matter what the IP's in the list are.

I'm sure it worked at least once, however I don't know what I changed to make it behave differently.

The function is as below:

function testIP($user_ip, $cidrs)   
{  
    $ipu = explode('.', $user_ip);  
    foreach ($ipu as &$v)  
        $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);  

    $ipu = join('', $ipu);  
    $res = false;  

    foreach ($cidrs as $cidr)   
    {  

        $parts = explode('/', $cidr);  

        if (empty($parts))  
        {  
            if (in_array($user_ip, $cidrs))  
            {  
                $res = true;  
                break;  
            } 
            break;         
        }  



        $ipc = explode('.', $parts[0]);  

        foreach ($ipc as &$v) $v = str_pad(decbin($v), 8, '0', STR_PAD_LEFT);  

        $ipc = substr(join('', $ipc), 0, $parts[1]);  

        $ipux = substr($ipu, 0, $parts[1]);  
        $res = ($ipc === $ipux);  
        if ($res) break;  
    }  
    return $res;  
}

I cannot for the life of me work out why it is no longer working - I have lost many hours over this!

Upvotes: 1

Views: 149

Answers (1)

000
000

Reputation: 27247

explode will always return an array. Your if (empty(... check is failing. Try if (count($parts)==1) then $res = in_array($user_ip, $cidrs)

Edit: Also, do not break, rather continue to the next cidr:

    if (count($parts)==1)
    {  
        if (in_array($user_ip, $cidrs))  
        {  
            $res = true;  
            break;  
        } 
        continue;         
    }  

Upvotes: 1

Related Questions