I'm making a page MVC
where the user can register, log in and edit their username, password and email, all good so far, in the navigation bar of the page there is a button called Users , which can only be accessed when you log in ,When the user logs in it does work, but if he is not logged in to the page, pressing the button should redirect you to the page to enter, but it throws me an error when this happens:
Notice: Undefined index: validate.
Warning: Cannot modify header information - headers already sent by(output started at C:\wamp...
This is the PHP code :
MODEL:
public static function vistaUsuariosModel($datosModel,$tabla){ $stmt= Conexion::conectar()->prepare("SELECT id,usuario,password,email FROM $tabla"); $stmt->execute(); return $stmt->fetchall(); $stmt->close(); }
VIEW:
<?php session_start(); if(!$_SESSION["validar"]){ header("location:index.php?action=ingresar"); exit(); } ?> <h1>USUARIOS</h1> <table border="1"> <thead> <tr> <th>Usuario</th> <th>Contraseña</th> <th>Email</th> <th>Editar</th> <th>Borrar</th> </tr> </thead> <tbody> <?php $b=new MvcController(); $b->vistaUsuariosController(); ?> </tbody> </table> <?php if(isset($_GET["action"])){ if($_GET["action"]== "cambio"){ echo "<h1>Actualización Exitosa</h1>"; } } ?>
CONTROLLER:
public static function ingresoUsuarioController(){ if(isset($_POST["usuarioIngreso"])){ $datosController = array("usuario"=>$_POST["usuarioIngreso"],"password"=>$_POST["passwordIngreso"]); $respuesta = Datos::ingresoUsuarioModel($datosController,"usuarios"); if($respuesta["usuario"]==$_POST["usuarioIngreso"] && $respuesta["password"]==$_POST["passwordIngreso"]){ session_start(); $_SESSION["validar"]=true; header("location:index.php?action=usuarios"); }else{ header("location:index.php?action=fallo"); } } }
I have tried to find the error, but I can't find it, if someone knows what it could be, it would be very helpful.
It
Notice: Undefined index: validar.
occurs because in your view you are doing:When the variable does not exist yet. To avoid this one option is:
Use
isset
, like this:Or, if you have
PHP v7
, use the operatorFusión de null (??)
( suggested by @Learner ), like so:Then the
Warning: Cannot modify header information - headers already sent...
arises because the has been printedNotice: Undefined index: validar.
and for the function toheader
work it is necessary that no outputs have occurred before its execution.In other words, the first warning message causes the second.
Solving the first warning, the second will also be solved.
Observation:
In your model you are closing the connection to the DB after doing
return
. That code will never run.If you really want to close the connection, you should do it like this:
It's worth mentioning that you don't need to close the connection, since it closes itself when the whole process finishes running.
Put this at the beginning
ob_start();
and this at the endob_end_flush();
And here the explanation: