Методы реализации условий IP в PHP с примерами кода

Метод 1: использование переменной $_SERVER

$ipAddress = $_SERVER['REMOTE_ADDR'];
// Example condition
if ($ipAddress == '127.0.0.1') {
    // IP address is localhost
    // Perform specific actions
} else {
    // IP address is not localhost
    // Perform other actions
}

Метод 2: использование функции filter_var()

$ipAddress = $_SERVER['REMOTE_ADDR'];
// Example condition
if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
    // IP address is valid IPv4
    // Perform specific actions
} else {
    // IP address is not valid IPv4
    // Perform other actions
}

Метод 3. Использование регулярных выражений

$ipAddress = $_SERVER['REMOTE_ADDR'];
// Example condition
if (preg_match('/^192\.168\.\d+\.\d+$/', $ipAddress)) {
    // IP address matches pattern 192.168.x.x
    // Perform specific actions
} else {
    // IP address does not match the pattern
    // Perform other actions
}

Метод 4. Использование сторонней библиотеки, например GeoIP

// Assuming you have GeoIP installed and configured
$ipAddress = $_SERVER['REMOTE_ADDR'];
$countryCode = geoip_country_code_by_name($ipAddress);
// Example condition
if ($countryCode == 'US') {
    // IP address is from the United States
    // Perform specific actions
} else {
    // IP address is not from the United States
    // Perform other actions
}