Home > Backend Development > PHP Tutorial > PHP code that uses IP to determine which city the visiting user is in

PHP code that uses IP to determine which city the visiting user is in

WBOY
Release: 2016-07-25 08:42:37
Original
1032 people have browsed it
  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. ?>
复制代码

是在, 哪个城市


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template