Heim  >  Artikel  >  Backend-Entwicklung  >  使用IP判断访问用户是在哪个城市的PHP代码

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

WBOY
WBOYOriginal
2016-07-25 08:42:37964Durchsuche
  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 : ([^}i', $content, $regs) ) {
  23. $city = $regs[1];
  24. }
  25. if ( preg_match('{
  26. State/Province : ([^}i', $content, $regs) ) {
  27. $state = $regs[1];
  28. }
  29. if( $city!='' && $state!='' ){
  30. $location = $city . ', ' . $state;
  31. return $location;
  32. }else{
  33. return $default;
  34. }
  35. }
复制代码

用法:

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

是在, 哪个城市


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php压缩CSS文件 Nächster Artikel:使用 mandrill 发送邮件的PHP代码