Error testing a session

1

I'm trying to get my login depending on what happens inside PHP so let me know if it's the email, or if the user is blocked, I'm developing this all in PHP, using as little javascript as possible. However, the first time you run the site it works, the second time you miss the login itself.

Follow the codes.

index.php

<!DOCTYPE html>
<?php 
    include 'scripts/help.php';
?>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
    <title>JR Tela de login</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><!--<scriptsrc="js/principal01.js"></script>-->
</head>
<body>
    <div class="container">
        <form class="form-signin" id="from" name="form" method="POST" action="scripts/validacao.php">
            <h2 class="form-signin-heading">JR Comunicações</h2>

            <div id="msg"><?php 
                //echo '<pre>'; print_r($_SESSION['msg']); die;

                if (isset($_SESSION)) {
                    get_msg('msg_login');
                }else{
                    echo "";
                }

                ?></div>


            <input type="text" name="TXT_ENDER_EMAIL" class="input-block-level" placeholder="Email">
            <input type="password" name="TXT_SENHA_USUAR" class="input-block-level" placeholder="Senha">
            <input class="btn btn-large btn-success" type="submit">
        </form>
    </div>

</body>
</html>

help.php

<?php
// Função para setar a mensagem
function set_msg($id, $msg, $tipo)
{
    session_start();

    if (isset($id)) {
       $_SESSION['id'] = $id;
       switch ($tipo) {

        case 'error':
            $_SESSION['msg'] = '<div class="alert-danger">' . $msg . '</div>';

            break;

        case 'alert':
            $_SESSION['msg'] = '<div class="alert-alert">' . $msg . '</div>';

            break;

        default:
            $_SESSION['msg'] = '<div class="alert-alert">' . $msg . '</div>';
            break;
        }
    }
}

// Esta função vai exibir sua mensagem onde você quiser
function get_msg($id) { 
    //echo '<pre>'; print_r($_SESSION['msg']); die;

        session_start();      

        if ($id == $_SESSION['id']) {

         if (isset($_SESSION['msg'])) {

          echo $_SESSION['msg']; 

            }

        return FALSE; 
        } 

}

?>

validation.php

<?php

include ("../includes/conexao.php");
include("help.php");

$email = ($_POST['TXT_ENDER_EMAIL']);
$senha = ($_POST['TXT_SENHA_USUAR']);

// Validação do usuário/senha digitados
$sql = "SELECT COD_IDENT_USUAR, TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, FLG_STATU_USUAR FROM tbl_USUARIOS WHERE TXT_ENDER_EMAIL = '".$email."' AND TXT_SENHA_USUAR = '".$senha."'";
$qr = mysql_query($sql);
if (mysql_num_rows($qr) != 1) {
    // Mensagem de erro quando os dados são inválidos e/ou o usuário não foi encontrado
    set_msg('msg_login', 'Login ou senha inválidos', 'error');
    header("Location: ../index.php"); exit; // Redireciona o visitante
} else {
    // Salva os dados encontados na variável $resultado
    $resultado = mysql_fetch_assoc($qr);


    // Se a sessão não existir, inicia uma
    if (!isset($_SESSION)) session_start();

    // Salva os dados encontrados na sessão
    $_SESSION['UsuarioID'] = $resultado['COD_IDENT_USUAR'];
    $_SESSION['UsuarioNome'] = $resultado['TXT_NOMEX_USUAR'];
    $_SESSION['UsuarioEmail'] = $resultado['TXT_ENDER_EMAIL'];
    $_SESSION['UsuarioFlag'] = $resultado['FLG_STATU_USUAR'];

    if($resultado['FLG_STATU_USUAR'] == 'A'){
    // Redireciona o visitante
    header("Location: ../paginas/principal.php"); exit;
    }else{
        set_msg('msg_login', 'Usuario bloqueado', 'error');
        header("Location: ../index.php"); exit; // Redireciona o visitante

    }
}
?>
    
asked by anonymous 11.06.2015 / 21:10

1 answer

4

First and foremost, always remember to post as many details as possible, for example:

  • Important code snippets
  • How your code should work and how it works
  • The errors occurred (not something like: did not work, did not stick, nothing happens)
  • Any dependency and / or lib that you use and find relevant

Response

In a few words, the solution to your problem is to start the session at the beginning of every file and / or layout you have, or in this case, at least index.php . >

But for a better understanding, please see the topics below:

session_start ();

Log in to the beginning of every file, not just your role. This way you can access the session items in any way, not just within your role where you were logging in.

So, your code looks like this:

index.php:

<?php session_start(); ?>
<!DOCTYPE html>
<?php include 'scripts/help.php'; ?>
<html>
<head>
    <meta charset="utf-8">

help.php:

<?php
// Função para setar a mensagem
function set_msg($id, $msg, $tipo)
{
    if ($id == $_SESSION['id']) {

     if (isset($_SESSION['msg'])) {

validation.php:

<?php session_start();

include ("../includes/conexao.php");
include("help.php");

// REMOVA esse código
// Se a sessão não existir, inicia uma
// if (!isset($_SESSION)) session_start();

Note [update]

So with the @ guilherme-natal you also mentioned, remove session_start() from within your file help.php and leave only index.php and validation.php .

The file help.php until then is used only to keep its functions useful, and how it is included in index.php the session is shared .

isset ()

Also as mentioned by the @ guilherme-nascimento , there is no need for you to check the existence of $_SESSION , aiming that you have already "startedou / started" it.

So you should check only if the index / key / key / value you want exists in the session, ie:

<?php
    if (isset($_SESSION['msg_login'])) {
        get_msg('msg_login');
    } else {
        echo "";
    }
?>
</div>

I hope I have helped.

Any questions, leave a comment below.

    
11.06.2015 / 21:57