-1

I'm working on a IP restriction plugin but having a strange problem.

I have a textarea in the settings page where each of the IP addresses that should be allowed are entered, one per line. I'm then parsing the IPs into an array like this:

$ips = trim($cmm_options['ips']);   
$ips = array_filter(explode("\n", $ips), 'trim');

This results in array that looks like this:

Array
(
    [0] => 67.6.134.102
    [1] => 97.118.69.236
)

When the page loads, the visitors IP address is checked against this array like this:

function cmm_ip_test($ips){

    //testing that correct IP address used
    for($i = 0, $cnt = count($ips); $i<$cnt; $i++) {
        $ipregex = preg_replace('/\./', '\.', $ips[$i]);
        $ipregex = preg_replace('/\*/', '.*', $ipregex);

        if(preg_match('/'.$ipregex.'/', $_SERVER['REMOTE_ADDR'])){
            // apply filter
            return true;
        }
        //do not apply filter
    }
    return false;
}

All of this works perfectly fine, with the exception of the first IP in the array. So for example, let's say my IP is 67.6.134.102 and it is the first one enter in the textarea (and so the first one in the array), like this the cmm_ip_test() function will return false. If I then move my IP to the second line (or any other but the first) of the textarea and load the page, cmm_ip_test() returns true.

From all that I can tell, there is absolutely no difference between the first index of the array and any past.

Any ideas why the first index position won't validate, even if it is a valid array?

Thanks!

1

There are two pieces to this code: 1) Interpreting the list of allowed IPs from a textarea, delimited by newline character, and 2) Checking if a given user's IP is in the allowed list of IPs.

Part 1) Parse list of IPs delimited by newline character, and trim whitespace:

$_POST['allowed_ips'] = "    67.6.134.102     
  97.118.69.236    ";

$ips = array_map('trim', explode("\n", $_POST['allowed_ips']));
var_dump($ips); //This should match your Array() output from above

Part 2) Check list of allowed IPs against the user's current IP:

var_dump(in_array($_SERVER['REMOTE_ADDR'], $ips));

in_array() allows you to take a string and check if it exists as a value in an array. Since you have a list of all IPs you want to allow, you just need to check if the user's current IP ($_SERVER['REMOTE_ADDR']) is in the array of allowed IPs.

  • Excellent! I am aware of in_array() and have used it quite a few times. No idea why I didn't think of it for this. It works great. Thanks! – Pippin Oct 11 '11 at 1:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.