Skip to content

API Reference

Rumen Damyanov edited this page Jul 31, 2025 · 1 revision

API Reference

Complete documentation of all classes, methods, and interfaces in the php-geolocation package.

Table of Contents

Geolocation Class

The main class for detecting and handling geolocation data.

Constructor

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');

Static Methods

simulate()

public static function simulate(
    string $country,
    array $countryToLanguage = [],
    string $languageCookieName = 'language',
    array $options = []
): self

Creates 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


Method Reference

Country Detection

getCountryCode()

public function getCountryCode(): ?string

Gets 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 null

Language Detection

getLanguageForCountry()

public function getLanguageForCountry(
    ?string $country,
    array $availableLanguages = []
): ?string

Gets 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)

getPreferredLanguage()

public function getPreferredLanguage(): ?string

Gets 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.

getAllLanguages()

public function getAllLanguages(): array

Gets all accepted languages from the browser.

Returns: Array of language codes in preference order

Example:

$languages = $geo->getAllLanguages();
// Returns: ["en-US", "en", "fr", "de"]

Client Information

getBrowser()

public function getBrowser(): ?array

Detects 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']}";
}

getOs()

public function getOs(): ?string

Detects 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.

getDeviceType()

public function getDeviceType(): ?string

Detects 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';
}

getResolution()

public function getResolution(): array

Gets 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']}";
}

Network Information

getIp()

public function getIp(): ?string

Gets 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)

Comprehensive Data

getGeoInfo()

public function getGeoInfo(array $fields = []): array

Gets 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]
]

Cookie Management

shouldSetLanguage()

public function shouldSetLanguage(): bool

Checks 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);
}

Development Tools

isLocalDevelopment()

public function isLocalDevelopment(): bool

Checks 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";
}

GeolocationSimulator Class

Utility class for generating realistic simulation data.

Constructor

public function __construct()

Creates a new simulator instance.

Methods

getRealisticDataForCountry()

public function getRealisticDataForCountry(string $country): array

Generates 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'
]

getAvailableCountries()

public function getAvailableCountries(): array

Gets 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
]

createCustomSimulation()

public function createCustomSimulation(array $options): array

Creates 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


Data Structures

Country Language Mapping

$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 Information Structure

[
    'browser' => string,    // Browser name
    'version' => string     // Version number
]

Resolution Structure

[
    'width' => int,         // Screen width in pixels
    'height' => int         // Screen height in pixels
]

Complete Geo Info Structure

[
    '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
]

Constants and Enums

Device Types

const DEVICE_DESKTOP = 'desktop';
const DEVICE_MOBILE = 'mobile';
const DEVICE_TABLET = 'tablet';

Browser Names

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';

Operating Systems

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';

Exception Handling

No Exceptions Thrown

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.

Error Handling Pattern

// 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';
    }
}

Validation Helpers

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;
}

Type Definitions

TypeScript-style Type Definitions

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';
}

PHP Doc Blocks

/**
 * @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

Usage Examples

Complete Implementation Example

<?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
}

Testing Example

// 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']
    );
}

Next Steps


Previous: Symfony Integration | Next: Configuration Reference

Clone this wiki locally