0

Here I am trying to get IP of user when he click login button on my page. I want to get city name finally from IP.

function get_client_ip() {
     $ipaddress = '';
     if ($_SERVER['HTTP_CLIENT_IP'])
         $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
     else if($_SERVER['HTTP_X_FORWARDED_FOR'])
         $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
     else if($_SERVER['HTTP_X_FORWARDED'])
         $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
     else if($_SERVER['HTTP_FORWARDED_FOR'])
         $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
     else if($_SERVER['HTTP_FORWARDED'])
         $ipaddress = $_SERVER['HTTP_FORWARDED'];
     else if($_SERVER['REMOTE_ADDR'])
         $ipaddress = $_SERVER['REMOTE_ADDR'];
     else
         $ipaddress = 'UNKNOWN';

     return $ipaddress; 
}

Is there any better and faster way other then above one?

And then to get city,

$ip = get_client_ip();
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
echo $details->city;
user123
  • 5,269
  • 16
  • 73
  • 121
  • You can download ip ranges related to cities and store them in db, so you can test the ip against the range in your local db, which will be faster for executing, but I don't think the effort worths – Royal Bg Nov 26 '13 at 09:06

1 Answers1

1
<?php
require_once("userip/ip.codehelper.io.php");
require_once("userip/php_fast_cache.php");

$_ip = new ip_codehelper();

$real_client_ip_address = $_ip->getRealIP();
$visitor_location       = $_ip->getLocation($real_client_ip_address);

$guest_ip   = $visitor_location['IP'];
$guest_country = $visitor_location['CountryName'];
$guest_city  = $visitor_location['CityName'];
$guest_state = $visitor_location['RegionName'];

echo "IP Address: ". $guest_ip. "<br/>";
echo "Country: ". $guest_country. "<br/>";
echo "State: ". $guest_state. "<br/>";
echo "City: ". $guest_city. "<br/>";

?>

for details take a look here http://www.a2zwebhelp.com/visitor-location-in-php

Suvash sarker
  • 3,140
  • 1
  • 18
  • 21