• Find out the region by IP address php. Sypex Geo - quick identification of a city by IP. Online services for geo-targeting

    In which my “bicycle” was mentioned, characterized by high speed. One of the popular questions was the possibility of determining a city by IP.

    And a few months later, the project that began as “for fun” grew into an independent project.
    A separate website dedicated to the Sypex Geo project has been opened, where you can download the latest versions of the API and databases, as well as read the documentation.

    For those who want to quickly test the correctness of determining the city by IP, here is a link to the demo page. And under the hack, I will describe some technical details and give the results of a little testing.

    Sypex Geo 2.1 format Since the publication of the last article, the Sypex Geo format (abbreviated as SxGeo) has been optimized, and the ability to include two directories in the database - cities and regions - has been added.

    When creating a new format, the following priorities were set:

    • high speed
    • low resource consumption
    • openness (specifications for the binary file format of the database and API are open)
    • versatility (the ability to create databases with any data sets)
    The format allows you to store data in different encodings. After leaving beta, scripts for converting a database from MySQL into a binary database file will be published.

    The following information is stored in the database:

    • Country ID
    • ISO 3166-1 country code (two characters)
    • FIPS 10-4 Region Code (two characters)
    • Region name (optional)
    • City
    • Latitude
    • Longitude
    • Timezone (optional)
    This list can be changed and/or expanded if necessary. More information about the SxGeo 2.1 format can be found on the website. Own database After a very close acquaintance with the popular GeoLite City geolocation system from MaxMind, it was decided to create our own database. The problem is that GeoLite City has a lot of inaccuracies, garbage, duplicate cities, excessive fragmentation of ranges, as well as problems with cities of the former USSR (for example, the names of companies or the names of those responsible from Whois are taken instead of cities).

    Currently the database is based on GeoLite City, but already contains completely redesigned coverage of Russia, Ukraine and Belarus. Other countries will be gradually specified, primarily the CIS and Europe. The Sypex Geo City database contains the names of cities and regions in Russian in UTF-8 (there are names that have not yet been translated), as well as timezone.

    In addition, other databases converted to SxGeo 2.1 format are available on the site.

    Usage Using the Sypex Geo API is as simplified as possible.
    1. Copy SxGeo.php and SxGeoCity.dat (or other databases) to the server 2. Connect the SxGeo.php file to your script by adding the line include("SxGeo.php"); 3. Create an SxGeo object //$SxGeo = new SxGeo(); // Default mode, database file SxGeo.dat $SxGeo = new SxGeo("SxGeoCity.dat", SXGEO_BATCH | SXGEO_MEMORY); // Fastest mode 4. Determine the city (SxGeo City, GeoLite City, IpGeoBase) $SxGeo->get($ip); (returns information about the city, without the name of the region and time zone) // $SxGeo->getCityFull($ip); (returns complete information about the city and region) Performance testing And for dessert, a little comparative performance testing. The opponents are GeoLite API and Geobaza API. All testing participants use a binary database of their own format, and use the PHP API. Testing takes place under Win 7 (proportions are maintained on Linux), PHP 5.2.17.

    Results after 10 runs for each API in two modes (normal and with memory caching), averaging and rounding to the nearest ten. For each run, an array of 50,000 random IP addresses is created, and each algorithm searches in a loop.

    Suggestions and wishes are welcome. We are also looking for people willing to help with porting the API to other languages ​​and creating modules for Apache and nginx.

    If you are going to make your own visitor statistics for your website, then you will probably want to know from which country your visitors come from. You can find out the visitor's country by his IP address, and in this article we will look at how this is done via PHP.

    There are two ways to find out the country by IP address via PHP. The first way is to use some WHOIS service, send a request to it and receive a response from it. The second option is to create your own table in the database, which will contain correspondence between IP addresses and countries. The pros and cons of the first and second methods are obvious, so I will not dwell on them. The second implementation method depends on your database and on the table in which the correspondence between IP addresses and countries is located. Therefore, we will consider the first method, since it is universal, although, of course, you will not be able to test this script on a local server without an Internet connection:

    Briefly, the principle: we find a service, look at how to send a request (what the variables are called, what method is used to send it), send a request via cURL, receive a response, extract the required line using regular expressions, and display the result. If you run this script, you will see the name of the country to which your IP address belongs. However, it is worth noting that it is not possible to find out the country for every IP address. It depends on the database that a particular WHOIS service uses. I’ll say right away that to test this script, you need to upload it to a remote server so that the IP address is not substituted: 127.0.0.1, since it will not work, because there is no country for it. Or simply replace the value of the $ip variable with some other IP address. As you can see, everything is very simple, the main thing here is to clearly choose one of two methods. If you want to find out a country by IP address through your database, then you need to find it first. There are quite a lot of them, so just search for them on the Internet. And if you are satisfied with using the WHOIS service and saving your server resources and space in the database, then you can use the code above, and by modifying the regular expression, you can pull out other data that this service produces, for example, the city.

    Hi all!

    I won’t say that often, but from time to time developers need to determine a city by IP in a PHP script.

    For example, you decided to make it easier for the user to enter contact information when placing an order in an online store. Or you want to set the site interface language depending on the country from which the visitor came to your site.

    Well, most often, determining a city by IP in PHP using GeoIP is probably needed by developers of various advertising networks in order to offer targeted advertising to users depending on their geographic location.

    I myself only needed to find out the country by IP in a PHP script once, when I decided to upload widgets of various social networks to the site for users from different countries. I will write more about why this was not needed and what happened in the end in the next article.

    In the meantime, let's talk about how many ways to determine a city and country by IP in PHP there are and what options for their implementation exist.

    PHP GeoIP - standard third-party functionality

    I specifically titled the description of the first method this way. The fact is that in PHP itself it is impossible to determine the city and country by IP address - the language does not have the necessary tools for this.
    But the official documentation has a hint on how to do this.

    PHP GeoIP is a third-party library that needs to be connected additionally, despite the fact that the description of the functions included in it is part of the official PHP documentation - http://php.net/manual/ru/ref.geoip.php

    In principle, the motives of PHP developers are quite clear.

    Firstly, the inclusion of this module in the language kit itself requires a large amount of server resources.

    Secondly, GeoIP PHP works based on a list of IP addresses corresponding to specific countries and cities. Therefore, GeoIP PHP requires constant support and expansion/modernization of the existing database, which would be an extra headache for PHP developers.

    Well, and thirdly, determining a city by IP in PHP is a feature that is rarely used in practice.

    As a result, due to these factors, PHP GeoIP is a third-party extension, the support of which and the creation of an API for integration on existing sites is carried out by the MaxMind company, a link to which is present in the description of this library.

    I will not describe the process of installing it on the server, because... I myself have not done this in practice, and the Internet is currently full of manuals for installing PHP GeoIP on both Linux and Windows servers.

    I can only say that this method of determining the city, country and other geo information by IP in PHP has two significant disadvantages:

  • Access to the database of complete information on IP addresses provided by MaxMind is paid. Moreover, the amount is in dollars, oddly enough :) Only significantly reduced options are available for free - http://dev.maxmind.com/geoip/geoip2/geolite2/
  • Considering that PHP GeoIP is a third-party extension, it will need to be installed separately on the server, which can become a difficult undertaking if shared hosting is used. You can, of course, contact technical support, but it’s not a fact that they will help you. For example, when I asked to install Sphinx, I was refused.
  • Determining a city by IP in PHP using alternative libraries

    Another way to find out a city by IP in a PHP script is to use alternative server libraries and information databases for IP addresses other than MaxMind.

    But they have the same disadvantages as the previous option, because... are just competitors of MaxMind. Access to databases and the ability to use their API are also paid. For free you can only get a list of countries and cities by IP, while with a paid plan you can get a wider list of data.

    The only advantage over PHP GeoIP is that these libraries are integrated in PHP code, and not at the server level, i.e. they can even be used on shared hostings.

    An example of such a library is provided by the db-ip.com service.

    By the way, the service I mentioned provides not only its PHP library for obtaining geodata from client IPs, but also access to information databases by addresses. So, in principle, no one is stopping you from using them in PHP GeoIP to use its API, but taking information from other sources.

    Well, and certainly no one is stopping you from writing your own parser of IP address database files to obtain information from them yourself, without any third-party permissions.

    How to determine a city by IP in PHP online

    Well, now I have come to the final method of how to find out the country by IP in PHP and other geo information, which I myself have used in practice.

    It consists of using API online services that allow you to receive data by IP address online.

    I decided to determine the city by IP in PHP using this method, because... it is devoid of the main drawback of the previous ones. Namely, it is the easiest to implement - you do not need to install or configure anything on the server, and, moreover, ask shared hosting technical support for this.

    In order to obtain the necessary information via IP, you just need to send a request to a specific URL and process the response.

    As for the cost of using them, for the most part they are also paid, because... work, as a rule, on the basis of existing commercial IP databases. But there are also free services that provide, perhaps, information as complete as commercial ones, but it can be obtained in an unlimited amount.

    True, they very quickly cease to exist, oddly enough, because It is very difficult to survive by providing such services. This was shown by my analysis of free online services for determining cities and countries by IP, which I carried out for personal purposes. They appeared on many sites, but when you tried to use them, it was clear that they had ceased to exist.

    In the end, I found what I needed, which is what I want to decide with you - http://www.geoplugin.com/

    This service allows you to both determine the city and other information by IP on the service website, and do this from code. Next, I will give an example of determining a country by IP in a PHP script using geoplugin.com. code is carried out using the code described in the article at the link.

    As you can see, the essence of the above code is to determine the client’s IP address, taking into account the possibility of connecting it through a proxy, and sending a request via the GeoPlugin API with further decoding and analysis of the results.

    In my example, as I already said, the result of this script will be the country code of the site client. In general, the complete list of returned parameters looks like this (for example, I decided to take the IP of the Novosibirsk region of the Russian Federation):

    ( "geoplugin_request":"195.208.128.3", "geoplugin_status":200, "geoplugin_credit":"Some of the returned data includes GeoLite data created by MaxMind, available from http:\/\/www.maxmind.com.", "geoplugin_city":"Novosibirsk", "geoplugin_region":"Novosibirsk", "geoplugin_areaCode":"0", "geoplugin_dmaCode":"0", "geoplugin_countryCode": "RU", "geoplugin_countryName":"Russian Federation", "geoplugin_continentCode":"EU", "geoplugin_latitude":"55.09", "geoplugin_longitude":"82.6519", "geoplugin_regionCode":"53", "geoplugin_regionName":" Novosibirsk", "geoplugin_currencyCode":"RUB", "geoplugin_currencySymbol":"rub", "geoplugin_currencySymbol_UTF8":"\u0440\u0443\u0431", "geoplugin_currencyConverter":58.9289 )

    As you can see, this service uses the previously mentioned MaxMind (geoplugin_credit parameter), but whether the information is paid or not is difficult to guess. On the one hand, the link to the source indicates that free access to the IP database is used, but, on the other hand, we see not only the country and city, but also a lot of other information, including the city, geographic coordinates, coordinates (langitude, latitude) , current currency and even its exchange rate.

    So this service can be called PHP GeoIP online. Its only difference from its server counterpart is that it receives information via IP a little slower due to the lack of server caching. But this does not mean that it is not on the GeoPlugin server itself 😉 So this drawback is rather symbolic.

    In any case, the GeoPlugin developers deserve applause, and, especially, for the fact that they didn’t even clutter their site with contextual advertising. Those. How they even survive is unclear. The only way to say “thank you” to them is to donate to your PayPal account.

    By the way, the PHP code I provided for determining a city by IP is universal. You can use it to obtain geodata using other services. The only thing you will need to change in it is the service API URL and the name of the necessary parameters that you will need to receive.

    That's all I have. Write your feedback on the article in the comments below and do not forget to share the post with your friends on social networks.

    P.S. : if you need a website or need to make changes to an existing one, but there is no time or desire for this, I can offer my services.

    More than 5 years of experience in professional website development. Working with PHP, OpenCart, WordPress, Laravel, Yii, MySQL, PostgreSQL, JavaScript, React, Angular and other web development technologies.

    Experience in developing projects at various levels: landing pages, corporate websites, online stores, CRM, portals. Including support and development of HighLoad projects. Send your applications by email [email protected].

    Continuing the topic about IP, this article will look at ways to determine the country, city and other geo-information about a user by his IP.

    GeoIP as a PHP extension

    Probably the most commonly used library for determining IP (office doc on php.net). It’s no wonder, because a binary database + compiled PHP extension works faster than all other methods.

    Installation on Ubuntu Server:

    Sudo apt-get install php5-geoip

    After installation, download the latest updates to the IP address database:

    After these steps, you need to restart PHP. This is necessary for the PHP interpreter to load the newly installed extension (php5-geoip) and new IP address databases.

    It is also necessary to periodically update the IP address database:

    Sudo wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz sudo gunzip GeoIP.dat.gz sudo mv GeoIP.dat /usr/share/GeoIP/

    After the update, you also need to restart PHP to apply the updated IP address database:

    Sudo service php5-fpm restart # if you are using NGINX # or sudo service apache2 restart # if you are using Apache

    Once GeoIP is installed, it can be used in code, like this: