Use IP to determine the PHP code of the city in which the user is accessing

Source: Internet
Author: User
  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. }
Copy Code

Usage:

    1. $ip = $_server[' remote_addr ');
    2. $city = detect_city ($IP);
    3. Echo $city;
    4. ?>
Copy Code

Yes, in which city?
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.