save an IP in a database

4

Good morning I'm trying to create a database to save the "likes" that the user gives. For this I need to save the IP so that the same person does not vote repeatedly.

The problem is that I get the IP but it does not save it (or at least it does not show it) I need help please. I pass the code to you:

alta.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
</head>
<body>

<?php
    function getRealIP()
    {

    if (isset($_SERVER["HTTP_CLIENT_IP"]))
    {
        return $_SERVER["HTTP_CLIENT_IP"];
    }
    elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
    {
        return $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    elseif (isset($_SERVER["HTTP_X_FORWARDED"]))
    {
        return $_SERVER["HTTP_X_FORWARDED"];
    }
    elseif (isset($_SERVER["HTTP_FORWARDED_FOR"]))
    {
        return $_SERVER["HTTP_FORWARDED_FOR"];
    }
    elseif (isset($_SERVER["HTTP_FORWARDED"]))
    {
        return $_SERVER["HTTP_FORWARDED"];
    }
    else
    {
        return $_SERVER["REMOTE_ADDR"];
    }

    }

     $ip= getRealIP();
    //echo $ip."<br/>"; 
    $_POST['ip']=$ip;
    echo $_POST['ip']."ESTE";//hasta aqui, bien
?>


  <form method="post" action="altab.php">
    Correo:<br/>
    <input type="text" name="correo" />
    <input type="hidden" id="dir" name="ip" >
    <input type="hidden"  name="fecha" >

    <input type="submit" value="listo">
  </form>


<script type="text/javascript">//aqui no entra o no hace nada
   var ip=<?php echo $ip; ?>;
   alert ("hola");
   alert(ip);
    document.getElementById("dir").value=ip;
</script>




</body>
</html>


altab.php
<?php 
header("Content-Type: text/html;charset=utf-8");
include('includes/conexion.php');//Incluimos la conexión
  $acentos = $enlace->query("SET NAMES 'utf8'");

  $query="INSERT INTO datos(correo,ip)  VALUES 
('{$_POST['correo']}','{$_POST['ip']}')";

if (mysqli_query($enlace,$query)){
                   echo $_POST['ip'];
                   echo 'hecho<br/><a href="index.php">Volver al Indice</a> <br/>';
                }
                else{
                    echo "<p>Hubo algún problema. Inténtelo más tarde</p>"; }

    ?>



listar.php
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<?php
header("Content-Type: text/html;charset=utf-8");
include('includes/conexion.php');//Incluimos la conexión
        $acentos = $enlace->query("SET NAMES 'utf8'");
        $query = "SELECT * FROM datos";

    if ($result = mysqli_query($enlace,$query)){
            while($fila = mysqli_fetch_array($result))
            {           
            echo "correo: ".$fila['correo']."<br/>";
            echo "IP: ".$fila['ip']."<br/>";
            echo "fecha: ".$fila['fecha']."<br/>";

            echo "<hr/>";
            }
        }
        ?>
<a href="index.php">Volver al Indice</a> <br/>
</body>
</html> 

the database is called "clients" and the table is "data"

CREATE TABLE IF NOT EXISTS 'datos' (
  'correo' varchar(50) COLLATE utf8_spanish_ci NOT NULL,
  'ip' varchar(15) COLLATE utf8_spanish_ci NOT NULL,
  'fecha' varchar(8) COLLATE utf8_spanish_ci NOT NULL,
  PRIMARY KEY ('correo')
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci;

Dump data for table datos

INSERT INTO 'datos' ('correo', 'ip', 'fecha') VALUES
('[email protected]', '', ''),
('[email protected]', '', ''),
('[email protected]', '', ''),
('[email protected]', '', '');
    
asked by Gema 19.06.2017 в 14:02
source

2 answers

2

I show you a code that I've tried in phpfiddle and it works.

I have applied some of the indications that your colleagues have made in comments, especially the queries prepared, to be able to enter your data safely.

Note: The second part of the code is just a test, to show that it works.

code

VIEW DEMO

<?php

require "util/public_db_info.php";

    $mysqli = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);

    /*
        * Las consultas preparadas sustituyen los valores reales
        * por signos de interrogación en MySQLi
    */
    $sql = "INSERT INTO datos (correo, ip) VALUES (?, ?)";    

    /*
        * Almacenar en variables los datos a insertar
        * Cambia las variables puestas a mano 
        * por las variables obtenidas por $_POST
    */
    $correo= "[email protected]";  //$_POST['email'];
    $ip= get_client_ip();         //$_POST['ip'];;

    //Preparar la consulta
    $stmt=$mysqli->prepare($sql);

    //Evaluar si  la preparación tuvo  éxito
    if ($stmt) 
    {
         /*
           * Pasar parámetros separados  de la instrucción SQL
           * la letras "ss" indican el tipo de cada dato que se va a insertar
           * s: String, si es una cadena , i: Integer, si fuera un entero, etc
           * Ejecutar
        */
        $stmt->bind_param("ss", $correo,$ip);
        $stmt->execute();

        /*
          * Imprimir la cantidad de filas insertadas usando affected_rows
        */

        printf("%d Filas insertadas.\n", $stmt->affected_rows);

        /*
         * Cerrar $stmt y luego la conexión
         * para liberar recursos
        */

    $stmt->close();
}

    // Comprobar si se insertaron los datos
    $sql = "SELECT * FROM datos";   

    if ($resultado = $mysqli->query($sql)) 
    {
           echo "<pre>";

        while ($row = mysqli_fetch_array($resultado))  
        {
           echo $row["correo"]." : ".$row["ip"];
        }

            echo "</pre>";

        $resultado->close();

    } 
       else 
    {
        echo "No hay datos";
    }

$mysqli->close();



    //Obtiene la IP del cliente

    function get_client_ip() {
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
           $ipaddress = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }
    ?>

result

-1 Filas insertadas.

[email protected] : 148.3.73.185
    
answered by 19.06.2017 / 15:43
source
0

You can do it in two different ways.

1- Assigning the variable via JAVASCRIPT, how you were already trying, but declaring the variables correctly.

<script type="text/javascript">//aqui no entra o no hace nada
   var ip = "<?php echo $ip; ?>";
   alert ("hola");
   alert(ip);
   document.getElementById("dir").value=ip;
</script>

2- Assigning the value directly in the field for this purpose.

<form method="post" action="altab.php">
    Correo:<br/>
    <input type="text" name="correo" />
    <input type="hidden" id="dir" name="ip" value="<?php echo $ip; ?>"> <!-- Podría ser <?=$ip?>, como fomra abreviada -->
    <input type="hidden"  name="fecha" > <!-- Aquí también puedes asignar el valor directamente al campo -->

    <input type="submit" value="listo">
</form>

Both forms are valid, but find the second most appropriate (personal opinion) because the assignment is direct and, unless you need to process this information with javascript, it is much easier.

    
answered by 19.06.2017 в 14:57