HS Banner
Back
Geo IP Filter

Author: Admin 04/18/2021
Language: PHP
Tags:


Description:

This is a geo IP filter for a PHP website.

Article:

This code snippet allows you to block countries based on their Geo IP location. it might not be the most efficient way to do it but it will work in a pinch.

//GeoIP Filter-----------------------------------------
if (isset($_SERVER['HTTP_CLIENT_IP'])){
    $client_ip = $_SERVER['HTTP_CLIENT_IP'];
} else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if(isset($_SERVER['HTTP_X_FORWARDED'])) {
    $client_ip = $_SERVER['HTTP_X_FORWARDED'];
} else if(isset($_SERVER['HTTP_FORWARDED_FOR'])) {
    $client_ip = $_SERVER['HTTP_FORWARDED_FOR'];
} else if(isset($_SERVER['HTTP_FORWARDED'])) {
    $client_ip = $_SERVER['HTTP_FORWARDED'];
} else if(isset($_SERVER['REMOTE_ADDR'])) {
    $client_ip = $_SERVER['REMOTE_ADDR'];
}

$cip = $client_ip;
$iptolocation = 'http://www.geoplugin.net/xml.gp?ip=' . $cip;
$location = file_get_contents($iptolocation);
if (strpos($location, 'United States') || strpos($location, 'Canada') || strpos($location, 'France') || strpos($location, 'Paris') || strpos($location, '::1')){
    // Don't block
}else{
    die('Access denied!');
}
//GeoIP Filter-----------------------------------------


Back
Comments
Add Comment
Admin
This is from the PHP manual.

$country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);

https://www.php.net/manual/en/function.geoip-country-code-by-name.php
Date: 04/19/2021