This tutorial shows you on how to import IP2Location DB3 (IP-Country-Region-City) into a MySQL database server and retrieve the geolocation information for viewing.
First of all, we assumed that the Laravel Framework and MySQL database server had been properly set up before following this tutorial.
-
- Download the IP2Location DB3 (IP-Country-Region-City) database from https://www.ip2location.com.
- Unzip the file and you shall find the IP-COUNTRY-REGION-CITY.CSV file.
- Create ip2location database and ip2location_db3 table in MySQL with the following SQL command:
CREATE DATABASE ip2location USE ip2location; CREATE TABLE `ip2location_db3`( `ip_from` INT(10) UNSIGNED, `ip_to` INT(10) UNSIGNED, `country_code` CHAR(2), `country_name` VARCHAR(64), `region_name` VARCHAR(128), `city_name` VARCHAR(128), INDEX `idx_ip_from` (`ip_from`), INDEX `idx_ip_to` (`ip_to`), INDEX `idx_ip_from_to` (`ip_from`, `ip_to`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
- Import the CSV data into ip2location_db3 table.
LOAD DATA LOCAL INFILE 'IP-COUNTRY-REGION-CITY.CSV' INTO TABLE`ip2location_db3` FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
- This will complete the IP2Location geolocation database set up. Now, we will move on the Lavarel framework part.
- Open the Lavarel database configuration file at config/database.php and update the connection information to your MySQL database.
- Create a UserController.php class at app/Http/Controllers folder with the below codes.
<?php namespace App\Http\Controllers; use DB; use App\User; use App\Http\Controllers\Controller; class UserController extends Controller { public function getIPLocation($ip_address) { $result = DB::select('SELECT * FROM `ip2location_db3` WHERE INET_ATON(?) <= ip_to LIMIT 1', array($ip_address)); return $result; } ?>
- We created one function named as getIPLocation that will accept an ip_address parameter for location lookup. And, this function will returns the location result to the caller.
- Next, we need to add the routing into app/Http/routes.php for the above controller class. Open the routes.php file and add the below code.
Route::get(‘ip/{ip_address}’, ‘UserController@getIPLocation’); - The above code will basically accept the ip/{ip_address} in url and pass the control to getIPLocation function inside UserController class for location retrieval.
- After that, you may try the solution by entering the url : http://YOUR_DOMAIN/ip/8.8.8.8.
- You shall see the result as below: