¿Cómo puedo detectar si el usuario está en localhost en PHP?


En otras palabras, ¿cómo puedo saber si la persona que usa mi aplicación web está en el servidor en el que reside? Si no recuerdo mal, phpMyAdmin hace algo como esto por razones de seguridad.

Author: Richie Marquez, 2010-01-13

8 answers

También puede usar $_SERVER['REMOTE_ADDR'] para la cual la dirección IP del cliente que solicita es dada por el servidor web.

$whitelist = array(
    '127.0.0.1',
    '::1'
);

if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
    // not valid
}
 132
Author: mauris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-21 02:19:21

Como complemento, como función...

function isLocalhost($whitelist = ['127.0.0.1', '::1']) {
    return in_array($_SERVER['REMOTE_ADDR'], $whitelist);
}
 17
Author: Jens Törnell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-18 14:25:50

$_SERVER["REMOTE_ADDR"] debe decirle la IP del usuario. Es falso, sin embargo.

Comprobar esta pregunta de recompensa para una discusión muy detallada.

Creo que lo que recuerda con phpMyAdmin es algo diferente: Muchos servidores MySQL están configurados para que solo se pueda acceder desde localhost por razones de seguridad.

 14
Author: Pekka 웃,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:13

Los usuarios más nuevos del sistema operativo (Win 7, 8) también pueden encontrar necesario incluir una dirección remota en formato IPV6 en su matriz de lista blanca:

$whitelist = array('127.0.0.1', "::1");

if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
    // not valid
}
 13
Author: reekogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 18:06:00

No parece que deba usar $_SERVER['HTTP_HOST'], porque este es el valor en el encabezado http, fácilmente falsificado.

También puedes usar $_SERVER["REMOTE_ADDR"], este es el valor más seguro, pero también es posible falsificar. Esta remote_addr es la dirección a la que Apache devuelve el resultado.

 6
Author: nicola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-18 11:31:52

Si desea tener una lista blanca / lista completa que soporte ips estáticas y nombres dinámicos.

Por ejemplo:

$whitelist = array("localhost", "127.0.0.1", "devel-pc.ds.com", "liveserver.com");
if (!isIPWhitelisted($whitelist)) die();

De esta manera se podría establecer una lista de nombres/IPs que será capaz (con seguridad) para ser detectado. Los nombres dinámicos añaden más flexibilidad para acceder desde diferentes puntos.

Aquí tiene dos opciones comunes, puede establecer un nombre en su archivo de hosts locales o simplemente puede usar uno proveedor de nombres dinámicos se puede encontrar en cualquier parte.

Esta función almacena en CACHÉ los resultados porque gethostbyname es una función muy lenta.

Para esta pupose he implementado esta función:

function isIPWhitelisted($whitelist = false)
{
    if ( isset($_SESSION) && isset($_SESSION['isipallowed']) )
        { return $_SESSION['isipallowed'];  }

    // This is the whitelist
    $ipchecklist = array("localhost", "127.0.0.1", "::1");
    if ($whitelist) $ipchecklist = $whitelist;

    $iplist = false;
    $isipallowed = false;

    $filename = "resolved-ip-list.txt";
    $filename = substr(md5($filename), 0, 8)."_".$filename; // Just a spoon of security or just remove this line

    if (file_exists($filename))
    {
        // If cache file has less than 1 day old use it
        if (time() - filemtime($filename) <= 60*60*24*1)
            $iplist = explode(";", file_get_contents($filename)); // Read cached resolved ips
    }

    // If file was not loaded or found -> generate ip list
    if (!$iplist)
    {
        $iplist = array(); $c=0;
        foreach ( $ipchecklist as $k => $iptoresolve )
        {
            // gethostbyname: It's a VERY SLOW function. We really need to cache the resolved ip list
            $ip = gethostbyname($iptoresolve);
            if ($ip != "") $iplist[$c] = $ip;
            $c++;
        }

        file_put_contents($filename, implode(";", $iplist));
    }

    if (in_array($_SERVER['REMOTE_ADDR'], $iplist)) // Check if the client ip is allowed
        $isipallowed = true;

    if (isset($_SESSION)) $_SESSION['isipallowed'] = $isipallowed;

    return $isipallowed;
}

Para una mejor confiabilidad, podría reemplazar el $_SERVER ['REMOTE_ADDR'] por el get_ip_address () que @Pekka mencionó en su post como "esta pregunta de recompensa"

 0
Author: Heroselohim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:13

Encontré una respuesta fácil.

Porque todas las unidades locales tienen C: o D: o F: ... sucesivamente.

Solo detecte si el segundo carácter es a :

if ( substr_compare(getcwd(),":",1,1) == 0)
{
echo '<script type="text/javascript">alert(" The working dir is at the local computer ")</script>';
    $client_or_server = 'client';
}
else
{
echo '<script type="text/javascript">alert(" The working dir is at the server ")</script>';
    $client_or_server = 'server';
}
 0
Author: Scoobeedo Cool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-03 21:19:12

¿Qué tal comparar $_SERVER['SERVER_ADDR'] === $_SERVER['REMOTE_ADDR'] para determinar si el cliente está en la misma máquina que el servidor?

 0
Author: Eugen Wesseloh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 12:05:35