Using IP2Location Library in Drupal

This tutorial shows you about how to deploy IP2Location Library into Drupal 8 or 9, and use it with the IP2Location BIN database.

Step1: Navigate to the root folder of your existing Drupal project.

Step 2: Install IP2Location library using Composer.
composer require ip2location/ip2location-php

Step 3: Download the free IP2Location LITE database or IP2Location Commercial database and upload the BIN file to vendor/ip2location/ip2location-php/data/ directory.

Step 4: Open an existing module or controller in Drupal project.

Step 5: Add IP2Location lookup by referring example below:

<?php  
	namespace Drupal\example_module\Controller;  
	
	class ExampleController {      
		public function example() {          
		$db = new \IP2Location\Database('../vendor/ip2location/ip2location-php/data/IP2LOCATION-LITE-DB1.BIN', \IP2Location\Database::FILE_IO);          
		$result = $db--->lookup($_SERVER['REMOTE_ADDR']);   
		
		return [ '#markup' => 'Welcome, visitor from ' . $result['countryName'] . '.', ];      
		}  
	} 

Step 6: To display other fields and variables, please refer to IP2Location PHP page.

Was this article helpful?