How to detect visitor's country from his IP for my PHP website right on the server

5,515

https://dev.maxmind.com/geoip/geoip2/geolite2/

This will give you a database of IP ranges and associated country. You can query this with PHP to find out the country for a given IP address.

Make sure you read the license conditions. You will also need to keep the data updated, as otherwise it will get less accurate over time.

Share:
5,515

Related videos on Youtube

Jasom Dotnet
Author by

Jasom Dotnet

Updated on September 18, 2022

Comments

  • Jasom Dotnet
    Jasom Dotnet over 1 year

    the problem:

    I need to detect visitor's country from his IP so I can display specific code based on the user location (different ads, etc.) in my PHP website.

    There is many different external services such as Ip-api.org which does this, but I want to do it internally on the server (it's faster).

    The question:

    How to do it? What do I need to install or what do google out?

    Update:

    Ideally with some open-source licence.

    • user020202
      user020202 almost 7 years
      I am not sure if this can be done just using PHP code as you can detect IP using the code but to detect country you might need to use external services to return the country of that IP.
    • Jasom Dotnet
      Jasom Dotnet almost 7 years
      @Goyllo This is not "recommendations for software" but "seeking for solution".
    • Jasom Dotnet
      Jasom Dotnet almost 7 years
      Same to @StephenOstermiller
    • Jasom Dotnet
      Jasom Dotnet almost 7 years
      @TopQnA I'm not interested in solo PHP code, I'm interested in whatever I can install on the server and has some connection with PHP.
    • Oskar Skog
      Oskar Skog almost 7 years
      Using IP addresses to determine the country is a tad unreliable. You need to make sure visitors can override the country setting. PS: You can't use the country to determine language. PPS: Tourists are in the wrong country and speak the wrong language, so they may need to change things manually. Make sure they can.
  • Jasom Dotnet
    Jasom Dotnet almost 7 years
    They require to put a link to the website but it's what I'm lookgin for.
  • Jasom Dotnet
    Jasom Dotnet almost 7 years
    The is probably the best answer, see this.
  • Jasom Dotnet
    Jasom Dotnet almost 7 years
    Worthy of mention is also this ip2location.com/developers/php see