Jump to content

I am getting undefined index error when i am trying to echo out the function.Help me. I am a PHP newbie.


ShashankGaurav

Recommended Posts

<?php

 

function ipchecker() {

 

$http_client = $_SERVER['HTTP_CLIENT_IP'];

$http_x_forwarderd_for = $_SERVER['HTTP_X_FORWARDED_FOR'];

$http_remote_addr= $_SERVER['REMOTE_ADDR'];

 

 

if (!empty($http_client)) {

 

     $ip_address=$http_client;

 

} else if (!empty($http_x_forwarderd_for)) {

 

     $ip_address=$http_x_forwarderd_for;

 

} else if (!empty($http_remote_addr)) {

 

 

      $ip_address= $http_remote_addr;


 

return $ip_address;

 

}

 

 

?>

Hi,

 

you cannot do the empty() check after you've tried to assign the array entry to a variable, because it's already too late then. The index error happens right when you access a nonexistent entry.

 

So you need to wrap the array expression itself into empty():

if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
}

Note that !empty($var) generally makes no sense if $var has been defined previously. This expression checks whether the variable exists and is truthy. Since it does exist, you can jump straight to the truthiness check:

if ($var)
{
    ...
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.