Protect my login against SQL injection [duplicate]

this question already has answers here : How to avoid SQL injection in PHP? (5 responses) Closed 3 years ago .

Greetings from before hand, I have been programming a digital platform, but checking its security I realized that a bug, it is vulnerable to a SQl injection, just putting 'or'1 '='1 in the username and password'or'1' = ' 1 could access without any problem, try to fix the bug, but I have not managed to fix it so far. I hope you can help me, thank you.

The following is part of the code of the login.

    <?php 

    if(!empty($_POST['usu']) and !empty($_POST['con'])){ 
        $usu=limpiar($_POST['usu']);
        $con=limpiar($_POST['con']);

        $pa=mysql_query("SELECT * FROM profesor WHERE doc='$usu' and con='$con'");              
        if($row=mysql_fetch_array($pa)){
            if($row['estado']=='s'){
                $nombre=$row['nom'];
                $nombre=explode(" ", $nombre);
                $nombre=$nombre[0];
                $_SESSION['user_name']=$nombre;
                $_SESSION['tipo_user']=$row['tipo'];
                $_SESSION['cod_user']=$row['doc'];
                echo mensajes('Bienvenido<br>'.$row['nom'].' '.$row['ape'].'<br> Accediendo, por favor espere...','verde').'<br>';
                echo '<center><img src="img/ajax-loader.gif"></center><br>';
                echo '<meta http-equiv="refresh" content="5;url=Principal.php">';
            }else{
                echo mensajes('Usted no se encuentra Activo en la base de datos<br>Consulte con su Administrador de Sistema','rojo');   
            }
        }else{
            echo mensajes('Usuario y/o Contraseña Incorrecto<br>','rojo');
            echo '<center><a href="index.php" class="btn"><strong>Intentar de Nuevo</strong></a></center>';
        }
    }else{
        echo '  <input type="text" name="usu" class="input-block-level" placeholder="Usuario" autocomplete="off style="text-align:center;" required>
                <input type="password" name="con" class="input-block-level" placeholder="Contraseña" autocomplete="off" required>
                <div align="right"><button class="btn btn-large btn-primary" type="submit"><strong>Ingresar</strong></button></div>';       
    }
  ?>
 0
Author: Juan Felipe Lopez Estrada, 2017-03-05

1 answers

I advise you to use prepared statements or PDO.

The idea of a native prepared statement is smart and simple: the query and data are sent to the server separately from each other, and therefore there is no chance of them interfering. Which makes the injection impossible.

The main and most essential benefit of prepared statements is the elimination of all the dangers of the manual format.

Warning: the extension mysql was deprecated on PHP 5.5.0 and removed on PHP 7.0.0. Extensions MySQLi or PDO_MySQL should be used instead.

Example prepared statement MySQLi:

Connection.php

$conexion = new mysqli("localhost", "usuario", "contraseña", "basedatos");

/* verificar conexión */
if (mysqli_connect_errno()) {
    printf("La conexión fallo: %s\n", mysqli_connect_error());
    exit();
}

You login:

<?php 
    session_start();

    //Reseteamos variables.
    $usu = $con = NULL;

    if (!empty($_POST['usu']) && !empty($_POST['con'])) { 

        //Añadimos la conexion.
        require_once'conexion.php';

        //Obtenemos datos formulario
        $usu = $_POST['usu'] ? : '';
        $con = $_POST['con'] ? : '';

        //Sentencia preparada.
        $stmt = $conexion->prepare("SELECT nom, ape, tipo, doc, estado FROM profesor WHERE doc=? AND con=? LIMIT 1");
        $stmt->bind_param("ss", $usu, $con); //Ligamos parametros marcadores (??)
        $stmt->execute();//Ejecutamos sentencia.

        //Comprobamos si existe dicho registro.
        $stmt->store_result();
        if ($stmt->num_rows === 1) {

            //Ligamos resultado desde la Base de datos.
            $stmt->bind_result($nombre, $apellido, $tipo, $doc, $estado);

            if ($stmt->fetch()) {

                if ($estado=='s') {

                    $_SESSION['user_name'] = $nombre;
                    $_SESSION['tipo_user'] = $tipo;
                    $_SESSION['cod_user'] = $doc;
                    echo 'Bienvenido<br>' . $nombre . ' ' . $apellido . '<br> Accediendo, por favor espere...', 'verde') . '<br>';
                    echo '<center><img src="img/ajax-loader.gif"></center><br>';
                    echo '<meta http-equiv="refresh" content="5;url=Principal.php">';

                } else {
                    echo 'Usted no se encuentra Activo en la base de datos.<br />Consulte con su Administrador de Sistema';
                }
            } $stmt->close(); //Cerramos sentencia

        } else {
            $stmt->close(); //Cerramos sentencia
            echo "Usuario y/o Contraseña Incorrecto<br>";
        }        

    }else{
        echo '  <input type="text" name="usu" class="input-block-level" placeholder="Usuario" autocomplete="off style="text-align:center;" required>
                <input type="password" name="con" class="input-block-level" placeholder="Contraseña" autocomplete="off" required>
                <div align="right"><button class="btn btn-large btn-primary" type="submit"><strong>Ingresar</strong></button></div>';       
    } 

?>
 3
Author: Diablo, 2017-03-05 15:08:09