1

enter image description here

I am not able to figure out why my condition is not working while the ip address is in the array. Why condition is failing as shown in image

<?php $valid_ip_list = explode(',',$this->valid_ips);
           echo $client_ip = $_SERVER['REMOTE_ADDR'];
           print('<pre>');
           print_r($valid_ip_list);
            if(in_array($client_ip ,$valid_ip_list))
                {
                    echo 'I am here';
                }
           else
                {
                    echo 'Condition fail';
                }
?>

Problem solved with the help of array_map('trim', explode(',', $valid_ips))

2
  • 1
    Check for white space characters in the ip list values... use var_dump() rather than echo and print_r to get more information Commented Dec 6, 2012 at 10:35
  • 1
    what does strlen($this->valid_ips[2]) give you? Or better, change print_r to var_dump and post the results. Commented Dec 6, 2012 at 10:48

1 Answer 1

3

This should help

$valid_ips = '192.100.100.61,192.100.100.2,127.0.0.1';

// authorized
if (in_array($_SERVER['REMOTE_ADDR'], array_map("trim", explode(',', $valid_ips)))) {
    //... 
}

// unauthorized
else {
    //...
}
Sign up to request clarification or add additional context in comments.

3 Comments

ips will be dynamic every time so i can not give static
is there any way to trim every element of array in explode
How does re-arranging the code help? It is still essentially the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.