0

This is homework - I'm trying to make a login with cookies so that the browser remembers that you previously logged in but I have no idea how to implement it into my code. And to logout how can I delete cookies to login again?

<?php
session_start();
require_once('conexion.php');

$usuario=$_POST['usuario'];
$contrasena=$_POST['pass'];
$con=md5($contrasena);


$consulta= "SELECT * FROM usuarios WHERE usuario='$usuario' and contrasena='$con'";
$result= mysqli_query($link, $consulta);
  $contador=0;

  while($fila = mysqli_fetch_array($result))
  {
    $contador=1;
    //cambiar por cookies
    $_SESSION['id']=$fila['id'];
    $_SESSION['nombre']=$fila['usuario'];
  }

    if($contador==0)
    {
        echo '<script type="text/javascript">window.location.assign("login.html");</script>';

    }else{
            echo '<script type="text/javascript">window.location.assign("index.html");</script>';
    }

    ?>

This is my form:

<form action="validacion.php" method="POST">
  <div class="form-group has-feedback">
    <input type="text" class="form-control" placeholder="Usuario" name="usuario" id="username">
    <span class="glyphicon glyphicon-user form-control-feedback"></span>
  </div>
  <div class="form-group has-feedback">
    <input type="password" class="form-control" placeholder="Contraseña" name="pass" id="password">
    <span class="glyphicon glyphicon-lock form-control-feedback"></span>
  </div>
  <div class="row">
    <div class="col-xs-8">
      <div class="checkbox icheck">
        <label>
              <input type="checkbox"> Remember Me
            </label>
      </div>
    </div>
    <!-- /.col -->
    <div class="col-xs-4">
      <button type="submit" class="btn btn-primary btn-block btn-flat">enter</button>
    </div>
    <!-- /.col -->
  </div>

</form>
Milo
  • 3,365
  • 9
  • 30
  • 44
  • Hi, I recommend you to check [this page](http://php.net/manual/es/reserved.variables.cookies.php) about `$_COOKIE` – Zyigh Sep 18 '18 at 15:46

1 Answers1

0

You should remember that sessions and cookies are not the same thing: What is the difference between Sessions and Cookies in PHP?

Still with me? You have to "set" a cookie on your validacion.php:

$username = $_POST['usuario']; //I would highly recommend that you clean the input. 

setcookie("usuario", $username);

On your index.html page simply convert it to a php file by adding the php at the top of the HTML. Add a php listener that detects a user that is logged in. Please also remember to change your index.html to index.php

<?php
  if (isset($_COOKIE["usuario"])) {
    echo "Welcome ".$_COOKIE["usuario"];
  }
?>

On your log out simply "unset" the cookies after making sure they exist.

if (isset($_COOKIE['usuario'])) {
   unset($_COOKIE['usuario']);
}

I would highly recommend you lookup: http://php.net/manual/en/function.setcookie.php &
http://php.net/manual/en/function.unset.php