problems with php header

Asked

Viewed 25 times

-1

Hello, I am studying php, and one of the tasks is that I need to do an authentication for some pages, I am using $_SESSIONS for this, and I wanted that if the values of $_SESSION['name'] $_SESSION['password'] were empty, to be redirected to the login page, but that’s not what happens, when I click to open the page without being logged in, the following occurs:

"Notice: Undefined index: name in E: xampp htdocs final hardware.php on line 3

Notice: Undefined index: password in E: xampp htdocs final hardware.php on line 4 authentication failure"

Does anyone have any idea what I can do? Below follows the code:

<?php
session_start();
$_SESSION['nome']=$_POST['nome'];
$_SESSION['senha']=$_POST['senha'];

if ($_SESSION['nome']=="abc" && $_SESSION['senha']=="abc")
{
    include ("cabecalho.php");
    echo "teste";
    include ("rodape.php");
    echo  "</div> </body> </html>";
}

elseif($_SESSION['nome'] == " " || $_SESSION['senha'] == " ")

{
    header("Location:login.php");
}

else
{
    echo "falha na autenticação";
}
?>

1 answer

0


If you open the direct page this will occur because the contents of the session "name" and "password" is loaded through a POST content (which did not occur). This is why the error of "Undefined index".

One of the ways to avoid this would be to create the name and password sessions and use the "isset" function to check if the POST exists and update its content. Your code would look like this:

<?php
session_start();
$_SESSION['nome']= "";
$_SESSION['senha']= "";
if (isset($_POST['nome'])){
    $_SESSION['nome']=$_POST['nome'];
}
if (isset($_POST['senha'])){
    $_SESSION['senha']=$_POST['senha'];
}

if ($_SESSION['nome']=="abc" && $_SESSION['senha']=="abc")
{
    include ("cabecalho.php");
    echo "teste";
    include ("rodape.php");
    echo  "</div> </body> </html>";
}

elseif($_SESSION['nome'] == " " || $_SESSION['senha'] == " ")

{
    header("Location:login.php");
}

else
{
    echo "falha na autenticação";
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.