简体   繁体   中英

Getting IP address with PHP to display correctly

I am trying to use the time and IP address to generate unique ID for users as they register for the site. The DB I'm using is MySQL and it comes with auto increment, but it doesn't seem like a practical technique for this. I am having issues with $_SERVER['REMOTE_ADDR'] returning an unreadable address. I'm getting symbols for the value in the firebug console. I tried using inet_ntop and inet_pton , neither worked.

$ip_address = $_SERVER['REMOTE_ADDR'];
$test = inet_ntop($ip_address);
echo($test);

Why am I getting symbols instead of readable text?

EDIT:

What I want to store is a combination of the IP and time. I need the IP to show in format of "79.104.97.105" -Niet the Dark Absol, but what I'm getting is if I use use inet_ntop or inet_pton or ::1 if I use just $_SERVER['REMOTE_ADDR'].

Two part question: 1) Am I getting the IP address as IPv6 if it returns ::1, 2) How do I convert to 127.0.0.1 which I think is IPv4

inet_ntop() expects the address in a binary format.

Example :

$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

You need to use inet_pton() instead, which expects the IP in for format in $_SERVER['REMOTE_ADDR'] .

Update

In the question you state that you need the address in readable format.

echo $_SERVER['REMOTE_ADDR'];

The variable already contains the IP in human readable format, no need for any PHP function to convert it.

You can try this function :

function getRealIP(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
      $ip = $_SERVER['HTTP_CLIENT_IP'];
    }else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
      $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

EDIT

This question may help you I think he had the same issue : Should a MAMP return ::1 as IP on localhost?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM