-
Notifications
You must be signed in to change notification settings - Fork 0
CodeIgniter Integration
Complete integration guide for using php-geolocation with CodeIgniter 3.x and 4.x, including hooks, controllers, helpers, and libraries.
- Installation & Setup
- CodeIgniter 4.x Integration
- CodeIgniter 3.x Integration
- Helper Functions
- Controller Integration
- Hooks Integration
- Language Integration
- Filter Integration (CI 4.x)
- View Integration
# In your CodeIgniter project root
composer require rumenx/php-geolocation- Download the package
- Copy to
application/third_party/geolocation/(CI 3.x) orapp/ThirdParty/geolocation/(CI 4.x) - Load the autoloader
Create app/Config/Services.php modification:
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
use Rumenx\Geolocation\Geolocation;
class Services extends BaseService
{
public static function geolocation(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('geolocation');
}
// Load configuration
$config = config('Geolocation');
return new Geolocation(
$_SERVER,
$config->countryToLanguage,
$config->cookieName
);
}
}Create app/Config/Geolocation.php:
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Geolocation extends BaseConfig
{
/**
* Country to language mapping
*/
public $countryToLanguage = [
'US' => ['en'], 'CA' => ['en', 'fr'], 'GB' => ['en'],
'DE' => ['de'], 'AT' => ['de'], 'CH' => ['de', 'fr', 'it'],
'FR' => ['fr'], 'BE' => ['fr', 'nl'], 'ES' => ['es'],
'IT' => ['it'], 'NL' => ['nl'], 'PT' => ['pt'], 'BR' => ['pt'],
'RU' => ['ru'], 'JP' => ['ja'], 'CN' => ['zh'],
];
/**
* Available languages for the application
*/
public $availableLanguages = ['en', 'fr', 'de', 'es'];
/**
* Default language
*/
public $defaultLanguage = 'en';
/**
* Cookie name for storing user language preference
*/
public $cookieName = 'ci_language';
/**
* Cookie lifetime in seconds (30 days)
*/
public $cookieLifetime = 2592000;
/**
* Enable simulation for local development
*/
public $enableSimulation = false;
/**
* Default simulation country
*/
public $simulationCountry = 'US';
/**
* Cache geolocation data
*/
public $cacheEnabled = true;
/**
* Cache lifetime in seconds
*/
public $cacheLifetime = 3600;
}Create app/Libraries/GeolocationService.php:
<?php
namespace App\Libraries;
use Rumenx\Geolocation\Geolocation;
use Rumenx\Geolocation\GeolocationSimulator;
use Config\Geolocation as GeolocationConfig;
class GeolocationService
{
protected $geolocation;
protected $config;
protected $cache;
public function __construct()
{
$this->config = config('Geolocation');
$this->cache = \Config\Services::cache();
$this->initializeGeolocation();
}
private function initializeGeolocation(): void
{
// Check for cached data first
if ($this->config->cacheEnabled) {
$cacheKey = $this->generateCacheKey();
$cached = $this->cache->get($cacheKey);
if ($cached) {
$this->geolocation = $this->createFromCache($cached);
return;
}
}
// Create new geolocation instance
if ($this->config->enableSimulation && $this->isLocalEnvironment()) {
$this->geolocation = Geolocation::simulate($this->config->simulationCountry);
} else {
$this->geolocation = new Geolocation(
$_SERVER,
$this->config->countryToLanguage,
$this->config->cookieName
);
}
// Cache the result
if ($this->config->cacheEnabled) {
$this->cacheGeolocationData();
}
}
public function getCountryCode(): string
{
return $this->geolocation->getCountryCode();
}
public function getLanguage(): string
{
$language = $this->geolocation->getLanguage();
// Ensure it's in available languages
if (!in_array($language, $this->config->availableLanguages)) {
return $this->config->defaultLanguage;
}
return $language;
}
public function getCity(): string
{
return $this->geolocation->getCity();
}
public function getRegion(): string
{
return $this->geolocation->getRegion();
}
public function setUserLanguage(string $language): bool
{
if (!in_array($language, $this->config->availableLanguages)) {
return false;
}
$response = \Config\Services::response();
return $response->setCookie([
'name' => $this->config->cookieName,
'value' => $language,
'expire' => $this->config->cookieLifetime,
'path' => '/',
'secure' => is_https(),
'httponly' => true,
'samesite' => 'Lax'
]);
}
public function getClientInfo(): array
{
return [
'country' => $this->getCountryCode(),
'language' => $this->getLanguage(),
'city' => $this->getCity(),
'region' => $this->getRegion(),
'browser' => $this->getBrowserInfo(),
'device' => $this->getDeviceType(),
'is_mobile' => $this->isMobile(),
'timezone' => $this->getTimezone()
];
}
public function isEurope(): bool
{
$euCountries = ['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE'];
return in_array($this->getCountryCode(), $euCountries);
}
public function requiresGDPR(): bool
{
return $this->isEurope();
}
public function getCurrencySymbol(): string
{
$currencies = [
'US' => '$', 'CA' => 'C$', 'GB' => '£', 'JP' => '¥',
'CN' => '¥', 'IN' => '₹', 'BR' => 'R$', 'AU' => 'A$',
'RU' => '₽', 'KR' => '₩', 'MX' => '$'
];
$country = $this->getCountryCode();
// EU countries use Euro
if ($this->isEurope() && !in_array($country, ['GB', 'SE', 'DK', 'NO', 'CH', 'PL', 'CZ', 'HU', 'RO', 'BG', 'HR'])) {
return '€';
}
return $currencies[$country] ?? '$';
}
public function formatPrice(float $amount): string
{
$symbol = $this->getCurrencySymbol();
return $symbol . number_format($amount, 2);
}
public function getWelcomeMessage(): string
{
$messages = [
'en' => 'Welcome',
'fr' => 'Bienvenue',
'de' => 'Willkommen',
'es' => 'Bienvenido',
'it' => 'Benvenuto',
'pt' => 'Bem-vindo',
'nl' => 'Welkom',
'ru' => 'Добро пожаловать',
'ja' => 'いらっしゃいませ',
'zh' => '欢迎'
];
return $messages[$this->getLanguage()] ?? $messages['en'];
}
private function getBrowserInfo(): array
{
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$browsers = [
'Chrome' => '/Chrome\/([0-9.]+)/',
'Firefox' => '/Firefox\/([0-9.]+)/',
'Safari' => '/Version\/([0-9.]+).*Safari/',
'Edge' => '/Edg\/([0-9.]+)/',
'Opera' => '/OPR\/([0-9.]+)/'
];
foreach ($browsers as $browser => $pattern) {
if (preg_match($pattern, $userAgent, $matches)) {
return [
'name' => $browser,
'version' => $matches[1]
];
}
}
return ['name' => 'Unknown', 'version' => ''];
}
private function getDeviceType(): string
{
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/Mobile|Android|iPhone/', $userAgent)) {
return 'mobile';
} elseif (preg_match('/Tablet|iPad/', $userAgent)) {
return 'tablet';
}
return 'desktop';
}
private function isMobile(): bool
{
return $this->getDeviceType() !== 'desktop';
}
private function getTimezone(): string
{
$timezones = [
'US' => 'America/New_York', 'CA' => 'America/Toronto',
'GB' => 'Europe/London', 'DE' => 'Europe/Berlin',
'FR' => 'Europe/Paris', 'ES' => 'Europe/Madrid',
'IT' => 'Europe/Rome', 'JP' => 'Asia/Tokyo',
'CN' => 'Asia/Shanghai', 'AU' => 'Australia/Sydney',
'BR' => 'America/Sao_Paulo', 'IN' => 'Asia/Kolkata',
'RU' => 'Europe/Moscow'
];
return $timezones[$this->getCountryCode()] ?? 'UTC';
}
private function generateCacheKey(): string
{
$factors = [
$_SERVER['HTTP_CF_IPCOUNTRY'] ?? '',
$_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '',
$_SERVER['REMOTE_ADDR'] ?? ''
];
return 'geo_' . hash('crc32', implode('|', $factors));
}
private function cacheGeolocationData(): void
{
$cacheKey = $this->generateCacheKey();
$data = [
'country' => $this->getCountryCode(),
'language' => $this->getLanguage(),
'city' => $this->getCity(),
'region' => $this->getRegion(),
'timestamp' => time()
];
$this->cache->save($cacheKey, $data, $this->config->cacheLifetime);
}
private function createFromCache(array $cached): Geolocation
{
$server = [
'HTTP_CF_IPCOUNTRY' => $cached['country'],
'HTTP_ACCEPT_LANGUAGE' => $cached['language']
];
return new Geolocation($server, $this->config->countryToLanguage, $this->config->cookieName);
}
private function isLocalEnvironment(): bool
{
$host = $_SERVER['HTTP_HOST'] ?? '';
return in_array($host, ['localhost', '127.0.0.1']) ||
strpos($host, '.local') !== false ||
strpos($host, '.dev') !== false;
}
}Create app/Filters/GeolocationFilter.php:
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use App\Libraries\GeolocationService;
class GeolocationFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$geo = new GeolocationService();
// Store geolocation data in request for controllers to use
$request->geoData = [
'country' => $geo->getCountryCode(),
'language' => $geo->getLanguage(),
'city' => $geo->getCity(),
'region' => $geo->getRegion(),
'client_info' => $geo->getClientInfo()
];
// Handle language switching
if ($request->getGet('lang')) {
$newLang = $request->getGet('lang');
if ($geo->setUserLanguage($newLang)) {
// Redirect to remove lang parameter from URL
$uri = $request->getUri();
$uri = $uri->removeQuery('lang');
return redirect()->to((string)$uri);
}
}
// Auto-redirect based on language preference (optional)
if ($arguments && in_array('auto_redirect', $arguments)) {
$this->handleLanguageRedirect($request, $geo);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Add geolocation headers for debugging
if (ENVIRONMENT === 'development') {
$geo = new GeolocationService();
$response->setHeader('X-Geo-Country', $geo->getCountryCode());
$response->setHeader('X-Geo-Language', $geo->getLanguage());
$response->setHeader('X-Geo-City', $geo->getCity());
}
return $response;
}
private function handleLanguageRedirect(RequestInterface $request, GeolocationService $geo): void
{
$currentPath = $request->getUri()->getPath();
$detectedLang = $geo->getLanguage();
// Check if URL already has language prefix
if (!preg_match('/^\/[a-z]{2}\//', $currentPath)) {
$newPath = '/' . $detectedLang . $currentPath;
redirect()->to($newPath)->send();
exit;
}
}
}Register the filter in app/Config/Filters.php:
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Filters extends BaseConfig
{
public $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'geolocation' => \App\Filters\GeolocationFilter::class,
];
public $globals = [
'before' => [
'geolocation'
],
'after' => [
'geolocation'
],
];
}<?php
namespace App\Controllers;
use App\Libraries\GeolocationService;
class Home extends BaseController
{
protected $geo;
public function __construct()
{
$this->geo = new GeolocationService();
}
public function index()
{
$data = [
'welcome_message' => $this->geo->getWelcomeMessage(),
'country' => $this->geo->getCountryCode(),
'language' => $this->geo->getLanguage(),
'city' => $this->geo->getCity(),
'client_info' => $this->geo->getClientInfo(),
'is_europe' => $this->geo->isEurope(),
'requires_gdpr' => $this->geo->requiresGDPR(),
'currency_symbol' => $this->geo->getCurrencySymbol()
];
return view('home', $data);
}
public function pricing()
{
$country = $this->geo->getCountryCode();
// Country-specific pricing
$pricing = $this->getCountryPricing($country);
$data = [
'country' => $country,
'currency' => $this->geo->getCurrencySymbol(),
'pricing' => $pricing,
'formatted_price' => $this->geo->formatPrice($pricing['monthly'])
];
return view('pricing', $data);
}
public function setLanguage()
{
$language = $this->request->getPost('language');
if ($this->geo->setUserLanguage($language)) {
return $this->response->setJSON(['success' => true]);
}
return $this->response->setJSON(['success' => false, 'error' => 'Invalid language']);
}
public function geoInfo()
{
return $this->response->setJSON($this->geo->getClientInfo());
}
private function getCountryPricing(string $country): array
{
$pricing = [
'US' => ['monthly' => 9.99, 'annual' => 99.99],
'GB' => ['monthly' => 7.99, 'annual' => 79.99],
'DE' => ['monthly' => 8.99, 'annual' => 89.99],
'FR' => ['monthly' => 8.99, 'annual' => 89.99],
'CA' => ['monthly' => 12.99, 'annual' => 129.99],
'AU' => ['monthly' => 14.99, 'annual' => 149.99],
];
return $pricing[$country] ?? $pricing['US'];
}
}Create application/libraries/Geolocation_lib.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . 'third_party/autoload.php';
use Rumenx\Geolocation\Geolocation;
use Rumenx\Geolocation\GeolocationSimulator;
class Geolocation_lib
{
protected $CI;
protected $geolocation;
protected $config;
public function __construct($params = array())
{
$this->CI =& get_instance();
$this->CI->load->config('geolocation');
$this->config = $this->CI->config->item('geolocation');
$this->initialize($params);
}
private function initialize($params)
{
// Merge config with params
$this->config = array_merge($this->config, $params);
// Check for simulation
if ($this->config['enable_simulation'] && $this->is_local_environment()) {
$this->geolocation = Geolocation::simulate($this->config['simulation_country']);
} else {
$this->geolocation = new Geolocation(
$_SERVER,
$this->config['country_to_language'],
$this->config['cookie_name']
);
}
}
public function get_country_code()
{
return $this->geolocation->getCountryCode();
}
public function get_language()
{
$language = $this->geolocation->getLanguage();
if (!in_array($language, $this->config['available_languages'])) {
return $this->config['default_language'];
}
return $language;
}
public function get_city()
{
return $this->geolocation->getCity();
}
public function get_region()
{
return $this->geolocation->getRegion();
}
public function set_user_language($language)
{
if (!in_array($language, $this->config['available_languages'])) {
return FALSE;
}
return $this->CI->input->set_cookie([
'name' => $this->config['cookie_name'],
'value' => $language,
'expire' => $this->config['cookie_lifetime'],
'path' => '/',
'secure' => is_https(),
'httponly' => TRUE
]);
}
public function get_client_info()
{
return [
'country' => $this->get_country_code(),
'language' => $this->get_language(),
'city' => $this->get_city(),
'region' => $this->get_region(),
'browser' => $this->get_browser_info(),
'device' => $this->get_device_type(),
'is_mobile' => $this->is_mobile(),
'timezone' => $this->get_timezone()
];
}
public function is_europe()
{
$eu_countries = ['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE'];
return in_array($this->get_country_code(), $eu_countries);
}
public function requires_gdpr()
{
return $this->is_europe();
}
public function get_currency_symbol()
{
$currencies = [
'US' => '$', 'CA' => 'C$', 'GB' => '£', 'JP' => '¥',
'CN' => '¥', 'IN' => '₹', 'BR' => 'R$', 'AU' => 'A$'
];
$country = $this->get_country_code();
if ($this->is_europe() && !in_array($country, ['GB', 'SE', 'DK', 'NO', 'CH'])) {
return '€';
}
return isset($currencies[$country]) ? $currencies[$country] : '$';
}
public function format_price($amount)
{
return $this->get_currency_symbol() . number_format($amount, 2);
}
public function get_welcome_message()
{
$messages = [
'en' => 'Welcome',
'fr' => 'Bienvenue',
'de' => 'Willkommen',
'es' => 'Bienvenido'
];
$language = $this->get_language();
return isset($messages[$language]) ? $messages[$language] : $messages['en'];
}
private function get_browser_info()
{
$user_agent = $this->CI->input->user_agent();
if ($this->CI->agent->is_browser('Chrome')) {
return ['name' => 'Chrome', 'version' => $this->CI->agent->version()];
} elseif ($this->CI->agent->is_browser('Firefox')) {
return ['name' => 'Firefox', 'version' => $this->CI->agent->version()];
} elseif ($this->CI->agent->is_browser('Safari')) {
return ['name' => 'Safari', 'version' => $this->CI->agent->version()];
}
return ['name' => 'Unknown', 'version' => ''];
}
private function get_device_type()
{
if ($this->CI->agent->is_mobile()) {
return 'mobile';
} elseif ($this->CI->agent->is_robot()) {
return 'robot';
}
return 'desktop';
}
private function is_mobile()
{
return $this->CI->agent->is_mobile();
}
private function get_timezone()
{
$timezones = [
'US' => 'America/New_York',
'GB' => 'Europe/London',
'DE' => 'Europe/Berlin',
'FR' => 'Europe/Paris',
'JP' => 'Asia/Tokyo'
];
$country = $this->get_country_code();
return isset($timezones[$country]) ? $timezones[$country] : 'UTC';
}
private function is_local_environment()
{
$host = $_SERVER['HTTP_HOST'];
return in_array($host, ['localhost', '127.0.0.1']) ||
strpos($host, '.local') !== FALSE;
}
}Create application/config/geolocation.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['geolocation'] = [
'country_to_language' => [
'US' => ['en'], 'CA' => ['en', 'fr'], 'GB' => ['en'],
'DE' => ['de'], 'AT' => ['de'], 'CH' => ['de', 'fr', 'it'],
'FR' => ['fr'], 'BE' => ['fr', 'nl'], 'ES' => ['es'],
'IT' => ['it'], 'NL' => ['nl'], 'PT' => ['pt'], 'BR' => ['pt']
],
'available_languages' => ['en', 'fr', 'de', 'es'],
'default_language' => 'en',
'cookie_name' => 'ci_language',
'cookie_lifetime' => 2592000, // 30 days
'enable_simulation' => FALSE,
'simulation_country' => 'US'
];<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('geolocation_lib');
$this->load->helper('geolocation');
}
public function index()
{
$data = [
'welcome_message' => $this->geolocation_lib->get_welcome_message(),
'country' => $this->geolocation_lib->get_country_code(),
'language' => $this->geolocation_lib->get_language(),
'city' => $this->geolocation_lib->get_city(),
'client_info' => $this->geolocation_lib->get_client_info(),
'is_europe' => $this->geolocation_lib->is_europe(),
'currency_symbol' => $this->geolocation_lib->get_currency_symbol()
];
$this->load->view('welcome_message', $data);
}
public function set_language()
{
$language = $this->input->post('language');
if ($this->geolocation_lib->set_user_language($language)) {
$this->output
->set_content_type('application/json')
->set_output(json_encode(['success' => TRUE]));
} else {
$this->output
->set_content_type('application/json')
->set_output(json_encode(['success' => FALSE, 'error' => 'Invalid language']));
}
}
public function geo_info()
{
$this->output
->set_content_type('application/json')
->set_output(json_encode($this->geolocation_lib->get_client_info()));
}
}Create app/Helpers/geolocation_helper.php:
<?php
use App\Libraries\GeolocationService;
if (!function_exists('geo_country')) {
function geo_country(): string
{
$geo = new GeolocationService();
return $geo->getCountryCode();
}
}
if (!function_exists('geo_language')) {
function geo_language(): string
{
$geo = new GeolocationService();
return $geo->getLanguage();
}
}
if (!function_exists('geo_city')) {
function geo_city(): string
{
$geo = new GeolocationService();
return $geo->getCity();
}
}
if (!function_exists('geo_welcome')) {
function geo_welcome(): string
{
$geo = new GeolocationService();
return $geo->getWelcomeMessage();
}
}
if (!function_exists('geo_currency')) {
function geo_currency(): string
{
$geo = new GeolocationService();
return $geo->getCurrencySymbol();
}
}
if (!function_exists('geo_price')) {
function geo_price(float $amount): string
{
$geo = new GeolocationService();
return $geo->formatPrice($amount);
}
}
if (!function_exists('geo_is_europe')) {
function geo_is_europe(): bool
{
$geo = new GeolocationService();
return $geo->isEurope();
}
}
if (!function_exists('geo_requires_gdpr')) {
function geo_requires_gdpr(): bool
{
$geo = new GeolocationService();
return $geo->requiresGDPR();
}
}
if (!function_exists('geo_client_info')) {
function geo_client_info(): array
{
$geo = new GeolocationService();
return $geo->getClientInfo();
}
}
if (!function_exists('geo_flag_emoji')) {
function geo_flag_emoji(): string
{
$flags = [
'US' => '🇺🇸', 'CA' => '🇨🇦', 'GB' => '🇬🇧', 'DE' => '🇩🇪',
'FR' => '🇫🇷', 'ES' => '🇪🇸', 'IT' => '🇮🇹', 'NL' => '🇳🇱',
'BR' => '🇧🇷', 'JP' => '🇯🇵', 'AU' => '🇦🇺'
];
return $flags[geo_country()] ?? '🌍';
}
}Create application/helpers/geolocation_helper.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('geo_country')) {
function geo_country()
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->get_country_code();
}
}
if (!function_exists('geo_language')) {
function geo_language()
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->get_language();
}
}
if (!function_exists('geo_welcome')) {
function geo_welcome()
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->get_welcome_message();
}
}
if (!function_exists('geo_currency')) {
function geo_currency()
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->get_currency_symbol();
}
}
if (!function_exists('geo_price')) {
function geo_price($amount)
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->format_price($amount);
}
}
if (!function_exists('geo_is_europe')) {
function geo_is_europe()
{
$CI =& get_instance();
if (!isset($CI->geolocation_lib)) {
$CI->load->library('geolocation_lib');
}
return $CI->geolocation_lib->is_europe();
}
}Create application/hooks/Geolocation_hook.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Geolocation_hook
{
public function initialize_geolocation()
{
$CI =& get_instance();
$CI->load->library('geolocation_lib');
// Store geo data in a global accessible way
$GLOBALS['geo_data'] = [
'country' => $CI->geolocation_lib->get_country_code(),
'language' => $CI->geolocation_lib->get_language(),
'city' => $CI->geolocation_lib->get_city(),
'region' => $CI->geolocation_lib->get_region()
];
// Handle language switching
if ($CI->input->get('lang')) {
$new_lang = $CI->input->get('lang');
if ($CI->geolocation_lib->set_user_language($new_lang)) {
// Redirect to remove lang parameter
$uri = $_SERVER['REQUEST_URI'];
$uri = preg_replace('/[?&]lang=[^&]*/', '', $uri);
redirect($uri);
}
}
// Auto-set language based on geolocation
$detected_lang = $CI->geolocation_lib->get_language();
$CI->config->set_item('language', $detected_lang);
}
}Register in application/config/hooks.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$hook['pre_controller'] = [
'class' => 'Geolocation_hook',
'function' => 'initialize_geolocation',
'filename' => 'Geolocation_hook.php',
'filepath' => 'hooks'
];Enable hooks in application/config/config.php:
$config['enable_hooks'] = TRUE;Create app/Controllers/Language.php:
<?php
namespace App\Controllers;
use App\Libraries\GeolocationService;
class Language extends BaseController
{
public function switch($language)
{
$geo = new GeolocationService();
if ($geo->setUserLanguage($language)) {
// Set session language
session()->set('language', $language);
// Redirect back to previous page
$redirect = $this->request->getGet('redirect') ?: previous_url();
return redirect()->to($redirect)->with('message', 'Language changed successfully');
}
return redirect()->back()->with('error', 'Invalid language selected');
}
public function detect()
{
$geo = new GeolocationService();
return $this->response->setJSON([
'detected_language' => $geo->getLanguage(),
'country' => $geo->getCountryCode(),
'available_languages' => config('Geolocation')->availableLanguages
]);
}
}Create language files in app/Language/:
app/Language/en/App.php:
<?php
return [
'welcome' => 'Welcome',
'pricing' => 'Pricing',
'contact' => 'Contact Us',
'about' => 'About Us'
];app/Language/fr/App.php:
<?php
return [
'welcome' => 'Bienvenue',
'pricing' => 'Tarification',
'contact' => 'Contactez-nous',
'about' => 'À propos'
];Use in views:
<h1><?= lang('App.welcome') ?></h1>
<p><?= geo_welcome() ?> <?= geo_flag_emoji() ?></p>Create app/Views/home.php:
<!DOCTYPE html>
<html lang="<?= geo_language() ?>">
<head>
<meta charset="UTF-8">
<title><?= geo_welcome() ?> - My Site</title>
</head>
<body class="country-<?= strtolower(geo_country()) ?> language-<?= geo_language() ?>">
<header>
<div class="location-info">
<?= geo_flag_emoji() ?>
<?= geo_city() ? geo_city() . ', ' : '' ?><?= geo_country() ?>
</div>
<div class="language-selector">
<form method="post" action="<?= base_url('language/switch') ?>">
<select name="language" onchange="this.form.submit()">
<option value="en" <?= geo_language() === 'en' ? 'selected' : '' ?>>English</option>
<option value="fr" <?= geo_language() === 'fr' ? 'selected' : '' ?>>Français</option>
<option value="de" <?= geo_language() === 'de' ? 'selected' : '' ?>>Deutsch</option>
<option value="es" <?= geo_language() === 'es' ? 'selected' : '' ?>>Español</option>
</select>
</form>
</div>
</header>
<main>
<h1><?= $welcome_message ?>!</h1>
<div class="geo-info">
<p><strong>Country:</strong> <?= $country ?></p>
<p><strong>Language:</strong> <?= $language ?></p>
<p><strong>City:</strong> <?= $city ?></p>
</div>
<?php if (geo_is_europe()): ?>
<div class="gdpr-notice">
<p>We use cookies to enhance your experience. By continuing to browse, you agree to our cookie policy.</p>
</div>
<?php endif; ?>
<div class="pricing-info">
<h2>Pricing</h2>
<p>Monthly: <?= geo_price(9.99) ?></p>
<p>Annual: <?= geo_price(99.99) ?></p>
</div>
<div class="client-info" style="display: none;">
<?= json_encode($client_info) ?>
</div>
</main>
<script>
// Access geo data in JavaScript
const geoData = <?= json_encode(geo_client_info()) ?>;
console.log('Client geo info:', geoData);
// Auto-hide GDPR notice after 5 seconds
<?php if (geo_requires_gdpr()): ?>
setTimeout(() => {
document.querySelector('.gdpr-notice').style.display = 'none';
}, 5000);
<?php endif; ?>
</script>
</body>
</html>Create application/views/welcome_message.php:
<!DOCTYPE html>
<html lang="<?= geo_language() ?>">
<head>
<meta charset="UTF-8">
<title><?= $welcome_message ?> - My CodeIgniter Site</title>
</head>
<body class="country-<?= strtolower($country) ?> language-<?= $language ?>">
<h1><?= $welcome_message ?>!</h1>
<div class="geo-info">
<p>Country: <?= $country ?></p>
<p>Language: <?= $language ?></p>
<p>City: <?= $city ?></p>
<p>Currency: <?= $currency_symbol ?></p>
</div>
<?php if ($is_europe): ?>
<div class="gdpr-notice">
<p>GDPR compliance is required for your location.</p>
</div>
<?php endif; ?>
<form method="post" action="<?= base_url('welcome/set_language') ?>">
<label>Change Language:</label>
<select name="language" onchange="this.form.submit()">
<option value="en" <?= $language === 'en' ? 'selected' : '' ?>>English</option>
<option value="fr" <?= $language === 'fr' ? 'selected' : '' ?>>Français</option>
<option value="de" <?= $language === 'de' ? 'selected' : '' ?>>Deutsch</option>
<option value="es" <?= $language === 'es' ? 'selected' : '' ?>>Español</option>
</select>
</form>
</body>
</html>- 🌍 Multi-language Websites - Complete internationalization examples
- ☁️ CloudFlare Setup - Configure CloudFlare headers
- 🔧 Troubleshooting - Common issues and solutions
- 📊 Analytics Integration - Track geolocation data
Previous: Pure PHP Integration | Next: CloudFlare Setup