Tutorial: Bloquear usuarios no deseados por Pais con Geoplugin(Opción Definitiva)

  • Autor Autor Darwin Mendoza
  • Fecha de inicio Fecha de inicio
Darwin Mendoza

Darwin Mendoza

Eta
Diseñador
Verificado
Verificación en dos pasos activada
Verificado por Whatsapp
Atención: Esta es una táctica muy "exagerada" por así decirlo, porque bloquearás el acceso a todo un País en específico por sólo unos pocos, pero si estas consciente de ello continúa leyendo.​


Hola!,

Como siempre, busco formas de proteger lo que me genera ingresos y este código me ha servido de mucho, así que aquí se los dejo, capas les ayude también. Con esto te ahorrarás el sobrecargo de "IPs" en el.htaccess(si es que lo usas).

- El proceso es sumamente sencillo, basta con crea dos nuevos archivos .php y añadir una linea de código a la página que desees el efecto.

1.- En el editor, abren un Nuevo archivo y agregan el siguiente código: (Una vez lo hayan pegado lo guardan con el nombre de geoplugin.class)

HTML:
<?php
 
class geoPlugin {
    
    //the geoPlugin server
    var $host = 'http://www.geoplugin.net/php.gp?ip={IP}&base_currency={CURRENCY}';
        
    //the default base currency
    var $currency = 'USD';
    
    //initiate the geoPlugin vars
    var $ip = null;
    var $city = null;
    var $region = null;
    var $areaCode = null;
    var $dmaCode = null;
    var $countryCode = null;
    var $countryName = null;
    var $continentCode = null;
    var $latitude = null;
    var $longitude = null;
    var $currencyCode = null;
    var $currencySymbol = null;
    var $currencyConverter = null;
    
    function geoPlugin() {
 
    }
    
    function locate($ip = null) {
        
        global $_SERVER;
        
        if ( is_null( $ip ) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        
        $host = str_replace( '{IP}', $ip, $this->host );
        $host = str_replace( '{CURRENCY}', $this->currency, $host );
        
        $data = array();
        
        $response = $this->fetch($host);
        
        $data = unserialize($response);
        
        //set the geoPlugin vars
        $this->ip = $ip;
        $this->city = $data['geoplugin_city'];
        $this->region = $data['geoplugin_region'];
        $this->areaCode = $data['geoplugin_areaCode'];
        $this->dmaCode = $data['geoplugin_dmaCode'];
        $this->countryCode = $data['geoplugin_countryCode'];
        $this->countryName = $data['geoplugin_countryName'];
        $this->continentCode = $data['geoplugin_continentCode'];
        $this->latitude = $data['geoplugin_latitude'];
        $this->longitude = $data['geoplugin_longitude'];
        $this->currencyCode = $data['geoplugin_currencyCode'];
        $this->currencySymbol = $data['geoplugin_currencySymbol'];
        $this->currencyConverter = $data['geoplugin_currencyConverter'];
        
    }
    
    function fetch($host) {
 
        if ( function_exists('curl_init') ) {
                        
            //use cURL to fetch data
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $host);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_USERAGENT, 'geoPlugin PHP Class v1.0');
            $response = curl_exec($ch);
            curl_close ($ch);
            
        } else if ( ini_get('allow_url_fopen') ) {
            
            //fall back to fopen()
            $response = file_get_contents($host, 'r');
            
        } else {
 
            trigger_error ('geoPlugin class Error: Cannot retrieve data. Either compile PHP with cURL support or enable allow_url_fopen in php.ini ', E_USER_ERROR);
            return;
        
        }
        
        return $response;
    }
    
    function convert($amount, $float=2, $symbol=true) {
        
        //easily convert amounts to geolocated currency.
        if ( !is_numeric($this->currencyConverter) || $this->currencyConverter == 0 ) {
            trigger_error('geoPlugin class Notice: currencyConverter has no value.', E_USER_NOTICE);
            return $amount;
        }
        if ( !is_numeric($amount) ) {
            trigger_error ('geoPlugin class Warning: The amount passed to geoPlugin::convert is not numeric.', E_USER_WARNING);
            return $amount;
        }
        if ( $symbol === true ) {
            return $this->currencySymbol . round( ($amount * $this->currencyConverter), $float );
        } else {
            return round( ($amount * $this->currencyConverter), $float );
        }
    }
    
    function nearby($radius=10, $limit=null) {
 
        if ( !is_numeric($this->latitude) || !is_numeric($this->longitude) ) {
            trigger_error ('geoPlugin class Warning: Incorrect latitude or longitude values.', E_USER_NOTICE);
            return array( array() );
        }
        
        $host = "http://www.geoplugin.net/extras/nearby.gp?lat=" . $this->latitude . "&long=" . $this->longitude . "&radius={$radius}";
        
        if ( is_numeric($limit) )
            $host .= "&limit={$limit}";
            
        return unserialize( $this->fetch($host) );
 
    }
 
    
}
 
?>

2.- Crean otro Nuevo .php con el nombre de geoip y en el colocan lo siguiente:

HTML:
<?php
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
$country_code = $geoplugin->countryCode;
switch($country_code) {
case '**': //Los dos asteriscos simulan el código ISO de cada país.(Ejemplo: Perú(PE))
header('Location: #'); //Michi simula la página que servirá de redirección tipo [B]404[/B]
exit;
case '**':
header('Location: #'); 
exit;
case '**':
header('Location: #'); 
exit;
}
?>
3. Abren con el Editor la página que quieran que se le restringa el código: (esto lo colocan arriba de <html>)

HTML:
<?php include("geoip.php"); ?>

Y listo! eso sería todo, lo que pueden hacer a partir de ahora es complementar este código, con el .htaccesss, para ponerle mayor seguridad a su sitio web. :witless:


Ya lo saben, preguntas en los comentarios y cualquier duda la responderé lo más pronto posible. 😀

Tema de la pregunta resuelta: Aquí.
 
sin tanto lió...
PHP:
<?php
	$MSG = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>';
	//ISO de los paises => http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
	$IP = $_SERVER['REMOTE_ADDR']; //Obtenemos la IP
	$DTO = json_decode(file_get_contents("http://www.telize.com/geoip/".$IP),true); //obtenemos los datos de la IP
	switch($DTO['country_code']) {
		case "AR":
			header("HTTP/1.0 404 Not Found"); //o header('location: otra url');
			die($MSG); //si colocamos una url a redireccionar no colocan $MSG
		case "RU":
			//lo mismo...
	}
?>

colocan eso arriba de todo de su index.php y listo... otra forma es usar geoip desde el server, pero necesitan un VPS o dedidaco para instalar el mod_geo
GeoIP Legacy Apache Module « Maxmind Developer Site
 
sin tanto lió...
PHP:
<?php
	$MSG = '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL was not found on this server.</p></body></html>';
	//ISO de los paises => http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
	$IP = $_SERVER['REMOTE_ADDR']; //Obtenemos la IP
	$DTO = json_decode(file_get_contents("http://www.telize.com/geoip/".$IP),true); //obtenemos los datos de la IP
	switch($DTO['country_code']) {
		case "AR":
			header("HTTP/1.0 404 Not Found"); //o header('location: otra url');
			die($MSG); //si colocamos una url a redireccionar no colocan $MSG
		case "RU":
			//lo mismo...
	}
?>

colocan eso arriba de todo de su index.php y listo... otra forma es usar geoip desde el server, pero necesitan un VPS o dedidaco para instalar el mod_geo
GeoIP Legacy Apache Module « Maxmind Developer Site
[MENTION=9679]cicklow[/MENTION], acabo de intentar bloquear el país dónde recido (Perú) y entro normal, ¿Estaré haciendo algo mal?.
Saludos.
 
[MENTION=9679]cicklow[/MENTION], acabo de intentar bloquear el país dónde recido (Perú) y entro normal, ¿Estaré haciendo algo mal?.
Saludos.

Pusiste 'PE' en mayúsculas? Otra cosa fíjate si telelize localiza tu ip
 
lo malo de usar geoplugin que te demora mucha la carga de la pagina :s
 
Atrás
Arriba