PHP - si no existe ip en archivo grabarla,caso contrario continuar

 
Vista:
Imágen de perfil de andres

si no existe ip en archivo grabarla,caso contrario continuar

Publicado por andres (2 intervenciones) el 03/10/2016 00:13:00
hola buenas necesito un ejemplo de como mirar si existe una ip en un archivo de texto y si No existe grabarla y en caso contrario de que ya exista no hacer nada con el archivo osea continuar con el flujo del programa.

tengo esto en un servidor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$ip=getRealIpAddr();
date_default_timezone_set('Europe/Madrid');//seteo para que me de la fecha de mi pais 
$fecha = date("d M Y H:i:s" );
$browser = $_SERVER['HTTP_USER_AGENT'];
$ruri = $_SERVER['REQUEST_URI'];
$servidor= $_SERVER['SERVER_NAME'];
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['PHP_SELF'];
$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
$latitud = $meta['geoplugin_latitude'];
$longitud = $meta['geoplugin_longitude'];
$ciudad = $meta['geoplugin_city'];
$region = $meta['geoplugin_region'];
$pais = $meta['geoplugin_countryName'];
$siglaspais = $meta['geoplugin_countryCode'];
$continente = $meta['geoplugin_continentCode'];
$moneda = $meta['geoplugin_currencyCode'];
$symbolMoneda = $meta['geoplugin_currencySymbol_UTF8'];
$abrefich = fopen("log.txt","a+" ) ;// a+ hago un append para no machacar datos 
 
fputs($abrefich,"Fecha: $fecha\r\nIp: $ip\r\nLatitud: $latitud\r\nLongitud: $longitud\r\nPais: $pais\r\nSiglaspais: $siglaspais\r\nContinente: $continente\r\nMoneda: $moneda $symbolMoneda\r\nCiudad: $ciudad\r\nRegion: $region\r\nNavegador: $browser\r\nUrl: $ruri\r\nServidor: $servidor\r\nHost: $host\r\nScript: $script\r\n***************************\r\n");
fclose($abrefich);


Va grabando en un archivo log.txt la longitud latitud ip y demas datos del usuario que entra.
queda en este estilo donde estan las xxxx hay datos reales que he cambiado para no publicarlos. ;

Fecha: 02 Oct 2016 23:10:50

Ip: xx.xx.xxx.157

Latitud: 40.4086

Longitud: -3.6922

Pais: Spain

Siglaspais: ES

Continente: EU

Moneda: EUR €

Ciudad: Madrid

Region: Autonomous Region of Madrid

Navegador: Mozilla/5.0 (Linux; Android 6.0.1; Build/MMB29M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.124 Mobile Safari/537.36

Url: /

Servidor: xxxxx.xxxxx.es

Host: xxxxx.xxxxx.es

Script: /index.php
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de kip
Val: 2.325
Plata
Ha disminuido 1 puesto en PHP (en relación al último mes)
Gráfica de PHP

si no existe ip en archivo grabarla,caso contrario continuar

Publicado por kip (877 intervenciones) el 03/10/2016 01:39:03
Hola, a ver si te sirve esta funcion:

1
2
3
4
5
6
7
8
9
function searchIp($file_path, $ip) {
    $file_search_lines = file("{$file_path}", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($file_search_lines as $line) {
        if (preg_match("/\b((ip)|(Ip))(:)?(\s)?({$ip})\b/", $line)){
            return TRUE;
        }
    }
    return FALSE;
}

Debes usarla de esta forma, segun tu codigo seria algo asi:

1
2
3
4
5
6
$ip = getRealIpAddr();
if (!searchIp("log.txt", $ip)) {
    echo 'NO SE HA ENCONTRADO LA IP';
} else {
    echo 'SE HA ENCONTRADO LA IP';
}

Nos cuentas si te sirvio.

Saludos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
2
Comentar
Imágen de perfil de andres

si no existe ip en archivo grabarla,caso contrario continuar

Publicado por andres (2 intervenciones) el 03/10/2016 14:22:55
Muchas gracias!! me sirvió de mucho lo acomode al programa, al if le quite el else pues no me hacia falta solo la primera comprobación.
Me va perfecto!! gracias de nuevo.

lo deje asi:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
function getRealIpAddr() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
 
$ip = getRealIpAddr();
date_default_timezone_set('Europe/Madrid');//seteo para que me de la fecha de mi pais 
$fecha = date("d M Y H:i:s" );
$browser = $_SERVER['HTTP_USER_AGENT'];
$ruri = $_SERVER['REQUEST_URI'];
$servidor= $_SERVER['SERVER_NAME'];
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['PHP_SELF'];
$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$ip));
$latitud = $meta['geoplugin_latitude'];
$longitud = $meta['geoplugin_longitude'];
$ciudad = $meta['geoplugin_city'];
$region = $meta['geoplugin_region'];
$pais = $meta['geoplugin_countryName'];
$siglaspais = $meta['geoplugin_countryCode'];
$continente = $meta['geoplugin_continentCode'];
$moneda = $meta['geoplugin_currencyCode'];
$symbolMoneda = $meta['geoplugin_currencySymbol_UTF8'];
 
 
 
function searchIp($file_path, $ip) {
    $file_search_lines = file("{$file_path}", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($file_search_lines as $line) {
        if (preg_match("/\b((ip)|(Ip))(:)?(\s)?({$ip})\b/", $line)){
            return TRUE;
        }
    }
    return FALSE;
}
if (!searchIp("log.txt", $ip)) {
$abrefich = fopen("log.txt","a+" ) ;// a+ hago un append para no machacar datos
fputs($abrefich,"Fecha: $fecha\r\nIp: $ip\r\nLatitud: $latitud\r\nLongitud: $longitud\r\nPais: $pais\r\nSiglaspais: $siglaspais\r\nContinente: $continente\r\nMoneda: $moneda $symbolMoneda\r\nCiudad: $ciudad\r\nRegion: $region\r\nNavegador: $browser\r\nUrl: $ruri\r\nServidor: $servidor\r\nHost: $host\r\nScript: $script\r\n***************************\r\n");
fclose($abrefich);
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar