-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
Complete documentation of all classes, methods, and interfaces in the php-geolocation package.
- Geolocation Class
- GeolocationSimulator Class
- Method Reference
- Data Structures
- Constants and Enums
- Exception Handling
- Type Definitions
The main class for detecting and handling geolocation data.
public function __construct(
array $server = [],
array $countryToLanguage = [],
string $languageCookieName = 'language'
)Parameters:
-
$server- Server variables (typically$_SERVER) -
$countryToLanguage- Mapping of countries to supported languages -
$languageCookieName- Name of the language cookie
Example:
$countryMapping = [
'US' => ['en'],
'DE' => ['de'],
'FR' => ['fr']
];
$geo = new Geolocation($_SERVER, $countryMapping, 'user_lang');public static function simulate(
string $country,
array $countryToLanguage = [],
string $languageCookieName = 'language',
array $options = []
): selfCreates a simulated geolocation instance for testing.
Parameters:
-
$country- Two-letter country code (ISO 3166-1 alpha-2) -
$countryToLanguage- Language mapping (optional) -
$languageCookieName- Cookie name (optional) -
$options- Additional simulation options (optional)
Options Array:
$options = [
'user_agent' => 'Custom User Agent String',
'languages' => ['de-DE', 'de', 'en'],
'ip_range' => '192.168.1.',
'resolution' => ['width' => 1920, 'height' => 1080],
'device' => 'desktop|mobile|tablet'
];Example:
$geo = Geolocation::simulate('DE', $countryMapping, 'lang', [
'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'languages' => ['de-DE', 'en']
]);Returns: Geolocation instance configured for simulation
public function getCountryCode(): ?stringGets the visitor's country code.
Returns: Two-letter country code or null if not detected
Example:
$country = $geo->getCountryCode();
// Returns: "US", "DE", "FR", etc. or nullpublic function getLanguageForCountry(
?string $country,
array $availableLanguages = []
): ?stringGets the preferred language for a specific country.
Parameters:
-
$country- Two-letter country code -
$availableLanguages- Array of languages your site supports
Returns: Language code or null if no match found
Example:
$language = $geo->getLanguageForCountry('DE', ['en', 'de', 'fr']);
// Returns: "de"
$language = $geo->getLanguageForCountry('CH', ['en', 'fr']);
// Returns: "fr" (first available from Switzerland's languages)public function getPreferredLanguage(): ?stringGets the browser's preferred language from Accept-Language header.
Returns: Primary language preference (e.g., "en-US") or null
Example:
$preferred = $geo->getPreferredLanguage();
// Returns: "en-US", "de-DE", "fr-FR", etc.public function getAllLanguages(): arrayGets all accepted languages from the browser.
Returns: Array of language codes in preference order
Example:
$languages = $geo->getAllLanguages();
// Returns: ["en-US", "en", "fr", "de"]public function getBrowser(): ?arrayDetects browser information from User-Agent header.
Returns: Array with browser details or null
Return Structure:
[
'browser' => 'Chrome|Firefox|Safari|Edge|Opera|Internet Explorer',
'version' => '91.0.4472.124'
]Example:
$browser = $geo->getBrowser();
if ($browser) {
echo "Browser: {$browser['browser']} v{$browser['version']}";
}public function getOs(): ?stringDetects operating system from User-Agent header.
Returns: Operating system name or null
Possible Values:
- "Windows 10", "Windows 11", "Windows 7"
- "macOS", "Mac OS X"
- "Linux", "Ubuntu", "CentOS"
- "Android", "iOS"
- "Chrome OS"
Example:
$os = $geo->getOs();
// Returns: "Windows 10", "macOS", "Linux", etc.public function getDeviceType(): ?stringDetects device type from User-Agent header.
Returns: Device type or null
Possible Values:
-
"desktop"- Desktop or laptop computer -
"mobile"- Mobile phone -
"tablet"- Tablet device
Example:
$device = $geo->getDeviceType();
switch ($device) {
case 'mobile':
$template = 'mobile.html.twig';
break;
case 'tablet':
$template = 'tablet.html.twig';
break;
default:
$template = 'desktop.html.twig';
}public function getResolution(): arrayGets screen resolution (simulated in development, real data not available from headers).
Returns: Array with width and height
Return Structure:
[
'width' => 1920,
'height' => 1080
]Example:
$resolution = $geo->getResolution();
if ($resolution['width'] && $resolution['height']) {
echo "Screen: {$resolution['width']}x{$resolution['height']}";
}public function getIp(): ?stringGets the visitor's IP address.
Returns: IP address string or null
Note: In local development, returns a simulated local IP. In production, returns the real IP from Cloudflare headers or standard sources.
Example:
$ip = $geo->getIp();
// Returns: "192.168.1.100" (local) or "203.0.113.1" (production)public function getGeoInfo(array $fields = []): arrayGets comprehensive geolocation and client information.
Parameters:
-
$fields- Array of specific fields to retrieve (optional, empty = all fields)
Available Fields:
-
country_code- Two-letter country code -
ip- IP address -
preferred_language- Primary browser language -
all_languages- All accepted languages -
browser- Browser information array -
os- Operating system -
device- Device type -
resolution- Screen resolution array
Returns: Array with requested information
Example:
// Get all information
$info = $geo->getGeoInfo();
// Get specific fields only
$basicInfo = $geo->getGeoInfo(['country_code', 'preferred_language']);
// Example return data
[
'country_code' => 'DE',
'ip' => '192.168.1.103',
'preferred_language' => 'de-DE',
'all_languages' => ['de-DE', 'de', 'en'],
'browser' => ['browser' => 'Chrome', 'version' => '91.0'],
'os' => 'Windows 10',
'device' => 'desktop',
'resolution' => ['width' => 1920, 'height' => 1080]
]public function shouldSetLanguage(): boolChecks if a language cookie should be set (i.e., cookie doesn't exist).
Returns: true if cookie should be set, false if it already exists
Example:
if ($geo->shouldSetLanguage()) {
$language = $geo->getLanguageForCountry($geo->getCountryCode());
setcookie('user_language', $language, time() + 86400 * 30);
}public function isLocalDevelopment(): boolChecks if running in local development environment.
Returns: true if local development, false if production
Detection Logic:
- Checks for local/private IP addresses
- Looks for development domains (localhost, .local, .dev)
- Verifies presence of Cloudflare headers
Example:
if ($geo->isLocalDevelopment()) {
echo "Simulation mode available";
// Show development tools
} else {
echo "Production mode - using real data";
}Utility class for generating realistic simulation data.
public function __construct()Creates a new simulator instance.
public function getRealisticDataForCountry(string $country): arrayGenerates realistic server data for a specific country.
Parameters:
-
$country- Two-letter country code
Returns: Array of server variables mimicking Cloudflare headers
Example:
$simulator = new GeolocationSimulator();
$data = $simulator->getRealisticDataForCountry('JP');
// Returns:
[
'HTTP_CF_IPCOUNTRY' => 'JP',
'HTTP_ACCEPT_LANGUAGE' => 'ja-JP,ja;q=0.9,en;q=0.8',
'HTTP_USER_AGENT' => '...',
'REMOTE_ADDR' => '192.168.1.105'
]public function getAvailableCountries(): arrayGets list of countries available for simulation.
Returns: Array mapping country codes to country data
Example:
$countries = $simulator->getAvailableCountries();
// Returns:
[
'US' => [
'name' => 'United States',
'language' => 'en-US',
'languages' => ['en-US', 'en'],
'user_agents' => [...]
],
'DE' => [
'name' => 'Germany',
'language' => 'de-DE',
'languages' => ['de-DE', 'de', 'en'],
'user_agents' => [...]
]
// ... more countries
]public function createCustomSimulation(array $options): arrayCreates custom simulation data with specific options.
Parameters:
-
$options- Array of custom simulation options
Options:
[
'country' => 'NL',
'language' => 'nl-NL',
'languages' => ['nl-NL', 'nl', 'en'],
'user_agent' => 'Custom Browser/1.0',
'ip' => '10.0.0.1'
]Returns: Array of server variables
$countryToLanguage = [
'US' => ['en'], // Single language
'CA' => ['en', 'fr'], // Multiple languages
'CH' => ['de', 'fr', 'it'], // Multiple languages
'BE' => ['fr', 'nl', 'de'], // Multiple languages
// ... more mappings
];[
'browser' => string, // Browser name
'version' => string // Version number
][
'width' => int, // Screen width in pixels
'height' => int // Screen height in pixels
][
'country_code' => string|null, // ISO 3166-1 alpha-2 country code
'ip' => string|null, // IP address
'preferred_language' => string|null, // Primary browser language
'all_languages' => array, // All accepted languages
'browser' => array|null, // Browser information
'os' => string|null, // Operating system
'device' => string|null, // Device type
'resolution' => array // Screen resolution
]const DEVICE_DESKTOP = 'desktop';
const DEVICE_MOBILE = 'mobile';
const DEVICE_TABLET = 'tablet';const BROWSER_CHROME = 'Chrome';
const BROWSER_FIREFOX = 'Firefox';
const BROWSER_SAFARI = 'Safari';
const BROWSER_EDGE = 'Edge';
const BROWSER_OPERA = 'Opera';
const BROWSER_IE = 'Internet Explorer';const OS_WINDOWS = 'Windows';
const OS_MACOS = 'macOS';
const OS_LINUX = 'Linux';
const OS_ANDROID = 'Android';
const OS_IOS = 'iOS';
const OS_CHROME_OS = 'Chrome OS';The php-geolocation package is designed to be resilient and does not throw exceptions under normal circumstances. All methods return null or appropriate default values when data is not available.
// Recommended error handling pattern
function safeGeolocation() {
try {
$geo = new Geolocation($_SERVER);
$country = $geo->getCountryCode();
return $country ?: 'US'; // Default fallback
} catch (Throwable $e) {
// Log error for debugging
error_log("Geolocation error: " . $e->getMessage());
// Return safe default
return 'US';
}
}function validateCountryCode(?string $country): bool {
return $country !== null &&
strlen($country) === 2 &&
ctype_alpha($country) &&
$country === strtoupper($country);
}
function validateLanguageCode(?string $language): bool {
return $language !== null &&
preg_match('/^[a-z]{2}(-[A-Z]{2})?$/', $language);
}
function validateGeoInfo(array $info): array {
$errors = [];
if (!validateCountryCode($info['country_code'] ?? null)) {
$errors[] = 'Invalid country code';
}
if (!validateLanguageCode($info['preferred_language'] ?? null)) {
$errors[] = 'Invalid language code';
}
if (!filter_var($info['ip'] ?? '', FILTER_VALIDATE_IP)) {
$errors[] = 'Invalid IP address';
}
return $errors;
}For reference, here are TypeScript-style definitions of the main types:
interface GeolocationInfo {
country_code?: string;
ip?: string;
preferred_language?: string;
all_languages: string[];
browser?: BrowserInfo;
os?: string;
device?: 'desktop' | 'mobile' | 'tablet';
resolution: Resolution;
}
interface BrowserInfo {
browser: string;
version: string;
}
interface Resolution {
width: number;
height: number;
}
interface CountryLanguageMapping {
[countryCode: string]: string[];
}
interface SimulationOptions {
user_agent?: string;
languages?: string[];
ip_range?: string;
resolution?: Resolution;
device?: 'desktop' | 'mobile' | 'tablet';
}/**
* @param array<string, string[]> $countryToLanguage
* @param string[] $availableLanguages
* @return string|null
*/
public function getLanguageForCountry(?string $country, array $availableLanguages = []): ?string
/**
* @param string[] $fields
* @return array<string, mixed>
*/
public function getGeoInfo(array $fields = []): array
/**
* @return array{browser: string, version: string}|null
*/
public function getBrowser(): ?array
/**
* @return array{width: int, height: int}
*/
public function getResolution(): array<?php
use Rumenx\Geolocation\Geolocation;
// Configuration
$countryMapping = [
'US' => ['en'], 'CA' => ['en', 'fr'], 'GB' => ['en'],
'DE' => ['de'], 'FR' => ['fr'], 'ES' => ['es'],
'JP' => ['ja'], 'BR' => ['pt'], 'CN' => ['zh']
];
$availableLanguages = ['en', 'fr', 'de', 'es'];
$cookieName = 'user_language';
// Initialize
$geo = new Geolocation($_SERVER, $countryMapping, $cookieName);
// Basic detection
$country = $geo->getCountryCode();
$language = $geo->getLanguageForCountry($country, $availableLanguages);
// Comprehensive information
$geoInfo = $geo->getGeoInfo();
// Cookie management
if ($geo->shouldSetLanguage() && $language) {
setcookie($cookieName, $language, time() + 86400 * 30, '/');
}
// Development mode detection
if ($geo->isLocalDevelopment()) {
// Show simulation tools or debug information
echo "Development mode: Country = {$country}, Language = {$language}";
}
// Client-specific logic
$browser = $geo->getBrowser();
$device = $geo->getDeviceType();
if ($device === 'mobile') {
// Mobile-specific handling
} elseif ($browser && $browser['browser'] === 'Safari') {
// Safari-specific handling
}// Test different countries
$testCountries = ['US', 'DE', 'FR', 'JP', 'BR'];
foreach ($testCountries as $country) {
$geo = Geolocation::simulate($country, $countryMapping);
$info = $geo->getGeoInfo(['country_code', 'preferred_language', 'device']);
printf(
"Country: %s | Language: %s | Device: %s\n",
$info['country_code'],
$info['preferred_language'],
$info['device']
);
}- ⚙️ Configuration - Advanced configuration options
- 📊 Client Detection - Detailed client information examples
- 🔧 Troubleshooting - Common issues and solutions
- 🌍 Multi-language Websites - Complete internationalization patterns
Previous: Symfony Integration | Next: Configuration Reference