viết hàm lấy địa chỉ ip và xác định thành phố từ địa chỉ ip bằng php?

Hiện tại mình đang muốn detect city bằng php mà không biết làm sao. Ai làm rồi giúp với.
code này nó không đúng ở tp hcm:

<?php
function get_ip() {
  //Just get the headers if we can or else use the SERVER global
  if ( function_exists( 'apache_request_headers' ) ) {
   $headers = apache_request_headers();
  } else {
   $headers = $_SERVER;
  }
  //Get the forwarded IP if it exists
  if ( array_key_exists( 'X-Forwarded-For', $headers ) && filter_var( $headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) {

   $the_ip = $headers['X-Forwarded-For'];
  } elseif ( array_key_exists( 'HTTP_X_FORWARDED_FOR', $headers ) && filter_var( $headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 )
  ) {
   $the_ip = $headers['HTTP_X_FORWARDED_FOR'];
  } else {
   $the_ip = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 );
  }
  return $the_ip;
 }
 
function detect_city($ip) {
   $json = @json_decode(file_get_contents("http://ipinfo.io/".$ip."/json"), true);
   return $json;
}
var_dump( detect_city(get_ip()));
 ?>
1 Like

test cái hàm ip thì đúng mà detect thì cứ sai

cái này do nhà cung cấp ip thui

cái này muốn chính xác tuyệt đối thì sài Geolocation á

OK. Google cả buổi cuối cùng cũng detect được cái city :pensive:

function detect_city($ip)
{
    $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
    if($query && $query['status'] == 'success') {
        return $query;
    }
}
2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?