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;

 

}

 

 

?>

Link to comment
Share on other sites

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)
{
    ...
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.