I want to retrieve information like the city, state, and country of a visitor from their IP address, so that I can customize my web page according to their location. Is there a good and reliable way to do this in PHP? I am using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
I've created a wrapper for ipinfo.io. You can install it using composer.
You can use it in this way:
I've done a bunch of testing with IP address services and here are a few ways I do it myself. First off a bunch off links to useful websites that I use:
https://db-ip.com/db Has a free ip-lookup service and has a few free csv files you can download. This uses a free api key that is attached to your email. It limits at 2000 queries per day.
http://ipinfo.io/ Free ip-lookup service without a api-key PHP functions:
In the end you get something like this:
http://www.geoplugin.com/ Slightly older but this service gives you a bunch of extra usefull information such as the currency off the country, continent code, longitude and more.
http://lite.ip2location.com/database-ip-country-region-city-latitude-longitude Offers a bunch of downloadable files with instructions to import them into your database. Once you have one off these files in your database you can select the data fairly easily.
Use the php function ip2long(); to turn the ip-address into a numeric value. For example 1.1.1.1 becomes 16843009. This lets you scan for the ip ranges given to you by the database file.
So in order to find out where 1.1.1.1 belongs to all we do is run this query:
This returns this data as a example.
I wrote a bot using an API from ipapi.co, here's how you can get location for an IP address (e.g.
1.2.3.4
) inphp
:Set header :
Get JSON response
of get a specific field (country, timezone etc.)
If you're searching for an updated/accurate database I recommend to use this one here because it was showing my exact location which was not included in many other services when I was testing.
(My city was
Rasht
and my country wasIran
with this ip address:2.187.21.235
when I was testing.)I recommend to use database rather than API methods, because it will be processed much faster locally.
Old post but still, i have tried almost all the services suggested here and the most accurate and fast i am using for production is: https://ip2location-api.com
They have Server and Client side solutions, JSON/XML/CSV/PHP formats, json ajax or javascript function callback, check out the documentation here
You can also use "smart-ip" service: