Problem with login

2

I'm trying to make a login with a database and PHP, which made progress and it seems to work, but lets me enter with any name and password.

I set the PHP of the server to 5.6 and I think the problem is using mysql_real_escape_string instead of mysqli_real_escape_string since in the tutorials of the work I did I use $mysqli = new mysqli(...) to connect.

Could you guide me to pass what I did to mysqli_real_escape_string ?

login.php

    <?php
session_start();

  // Obtengo los datos cargados en el formulario de login.
  $nombre = $_POST['nombre'];
  $password = $_POST['password'];
// // Datos para conectar a la base de datos.
   $nombreServidor =3333333 ;
   $nombreUsuario = 3333333;
   $passwordBaseDeDatos =3333333 ;
   $nombreBaBaseDeDatos=3333333;

  // // Crear conexión con la base de datos.
   $conn = new mysqli($nombreServidor, $nombreUsuario, $passwordBaseDeDatos, $nombreBaseDeDatos);

  // // Validar la conexión de base de datos.
   if ($conn ->connect_error) {
     die("Connection failed: " . $conn ->connect_error);
  }


  // Consulta segura para evitar inyecciones SQL.
  $sql = sprintf("SELECT * FROM usuarios WHERE nombre ='%s' AND password ='%s'", mysql_real_escape_string($nombre), mysql_real_escape_string($password));
  $resultado = $conn->query($sql);

  // Verificando si el usuario existe en la base de datos.
  if($resultado){
    // Guardo en la sesión el email del usuario.
    $_SESSION['nombre'] = $nombre;

    // Redirecciono al usuario a la página principal del sitio.
    header("HTTP/1.1 302 Moved Temporarily");
    header("Location: principal.php");
  }else{
    echo 'El usuario o password es incorrecto, <a href="index.html">vuelva a intenarlo</a>.<br/>';
  }

?>

index.html

<!DOCTYPE html>
<html lang="es">
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Control Service Robert</title>
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="publica/css/bootstrap.min.css">
    <link rel="stylesheet" href="publica/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="publica/estilos3.css">
      <!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="publica/js/bootstrap.min.js"></script>
</head>
<body>
    <header id="header" class="">
        <h1>Control Service Robert</h1>
    </header>
<div class="wrapper">
<div class="imagen" >
    <img src="img/tec.png" alt="tecnico">
  </div>
    <form class="form-signin" method="POST" action="login.php">

      <h2 class="form-signin-heading">Please login</h2>
      <input type="text" class="form-control" name="nombre" placeholder="Usuario" required="" autofocus="" /><br>
      <input type="password" class="form-control" name="password" placeholder="Password" required=""/>
      <label class="checkbox">
        <input type="checkbox" value="remember-me" id="rememberMe" name="rememberMe">Recuérdame
      </label>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
    </form>


</div>


<footer>






</footer>



</body>
</html>

cerrarseccion.php

<?php
  session_start();
// Elimina la variable email en sesión.
  unset($_SESSION['nombre']);

  // Elimina la sesion.
  session_destroy();

  // Redirecciona a la página de login.
  header("HTTP/1.1 302 Moved Temporarily");
  header("Location: index.html");
?>

In the principal.php start with this code:

<?php
session_start();
// Controlo si el usuario ya está logueado en el sistema.
  if(isset($_SESSION['nombre'])){
    // Le doy la bienvenida al usuario.
    echo 'Bienvenido <strong>'. $_SESSION['mombre'] .'</strong>, <a href="cerrarseccion.php">cerrar sesión</a>';
  }else{
    // Si no está logueado lo redireccion a la página de login.
    header("HTTP/1.1 302 Moved Temporarily");
    header("Location: index.html");
  }

The other pages the connection is with this one:

    <?php
    $mysqli = new mysqli('eeeee','eeeee','eeeeee','eeeeeee');

$mysqli->set_charset('utf8');
       if($mysqli->connect_error){

        die('Error en la conexion' . $mysqli->connect_error);
    }

?>
    
asked by kuky 28.09.2018 в 07:07
source

2 answers

1

Using mysqli_real_escape_string() requires the connection as the first parameter if you do not use the OOP interface.

In your case, when using it, you should use the correct method of $conn :

<?php
$sql = sprintf(
  "SELECT * FROM usuarios WHERE nombre ='%s' AND password ='%s'",
  $conn->real_escape_string($nombre),
  $conn->real_escape_string($password)
);

To continue, the problem you enter using the username and password that is not related to the use or not of one function or another, is related to that only checks if the query was executed correctly, not if it was found a user, so you have to get the registration with mysqli_result::fetch_assoc() :

<?php
$resultado = $conn->query($sql);
/* Comprobamos si se ejecutó correctamente la consulta */
if ($resultado !== false) {
  /* Verificando si el usuario existe en la base de datos. */
  $registro = $resultado->fetch_assoc();
  if ($registro !== null) {
    // Guardo en la sesión el email del usuario.
    $_SESSION['nombre'] = $registro['nombre'];
    // Redirecciono al usuario a la página principal del sitio.
    header("HTTP/1.1 302 Moved Temporarily");
    header("Location: principal.php");
  } else {
    echo 'El usuario o password es incorrecto, <a href="index.html">vuelva a intentarlo</a>.<br/>';
  }
} else {
  die('Error SQL: ' . htmlspecialchars($conn->error));
}

When obtaining the record, it will be worth null if the match was not found and in case of finding it, the data of the name will be in $registro['nombre'] .

    
answered by 28.09.2018 / 07:25
source
0

You have to validate that the result returns at least one row:

// Verificando si el usuario existe en la base de datos.    
if ($resultado && $resultado->num_rows == 1) {
    
answered by 28.09.2018 в 07:13