当前位置:Gxlcms > PHP教程 > 使用IP判断访问用户是在哪个城市的PHP代码

使用IP判断访问用户是在哪个城市的PHP代码

时间:2021-07-01 10:21:17 帮助过:55人阅读

  1. function detect_city($ip) {
  2. $default = 'UNKNOWN';
  3. $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
  4. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
  5. $ch = curl_init();
  6. $curl_opt = array(
  7. CURLOPT_FOLLOWLOCATION => 1,
  8. CURLOPT_HEADER => 0,
  9. CURLOPT_RETURNTRANSFER => 1,
  10. CURLOPT_USERAGENT => $curlopt_useragent,
  11. CURLOPT_URL => $url,
  12. CURLOPT_TIMEOUT => 1,
  13. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  14. );
  15. curl_setopt_array($ch, $curl_opt);
  16. $content = curl_exec($ch);
  17. if (!is_null($curl_info)) {
  18. $curl_info = curl_getinfo($ch);
  19. }
  20. curl_close($ch);
  21. if ( preg_match('{
  22. City : ([^<]*)
  23. }i', $content, $regs) ) {
  24. $city = $regs[1];
  25. }
  26. if ( preg_match('{
  27. State/Province : ([^<]*)
  28. }i', $content, $regs) ) {
  29. $state = $regs[1];
  30. }
  31. if( $city!='' && $state!='' ){
  32. $location = $city . ', ' . $state;
  33. return $location;
  34. }else{
  35. return $default;
  36. }
  37. }

用法:

  1. $ip = $_SERVER['REMOTE_ADDR'];
  2. $city = detect_city($ip);
  3. echo $city;
  4. ?>

是在, 哪个城市

人气教程排行