Error while testing a session

Asked

Viewed 124 times

1

I am trying to get my login depending on what happens in the internal part of PHP I warn if it is the email, or if the user is blocked, I am developing this all in PHP, using as little as possible javascript. However, the first time you run the site works, the second time you get the login wrong.

Follows 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>

    <!--<script src="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; 
        } 

}

?>

php validation.

<?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

    }
}
?>
  • Friend I will not answer clearly, because it seems to me that the problem is in your understanding at the time of developing, but I can give you some tips: The moment you use session_start the super global variable $_SESSION is already available, so isset($_SESSION) makes no sense. if (isset($id)) { within the function set_msg also makes no sense (except for the question of NULL)

  • @Guilhermenascimento is not working when I ask to give isset($_SESSION), and the first time I went around the page, but after I clicked on Ubmit, it goes and comes to me with the session and the values set.

  • I need when he comes back from Submit he appears on the screen, I tried to do it this way, but he accuses that the session is invalid, if in case I select a value for him it is the same, only appearing a value

  • Renan I did not give you the solution, I informed you that the use of some issets and the variable $_SESSION are wrong (no logic or need), I’m not criticizing you, I’m just telling you that it doesn’t make sense/need the way you put in the code and in my view the code itself is only a problem because of your understanding (or lack of it) about the use of super-global (http://php.net/manual/en/language.variables.superglobals.php) and function isset (http://php.net/manual/en/function.isset.php) and as much as I can help you fix the code, the problem goes beyond this.

  • The more help me to find the error, I turn, I try to test more I can not..

  • It cannot, because the code has no logic (no offense), the use of the superglobal variable called $_SESSION and some issets, I’m sorry, is not my ill will, I’m just giving you the preview of where you can find the problem, since it is not a problem necessarily of your code, but of your understanding of superglobal+isset. Perhaps some other contributor will provide a clearer answer. But the way to the solution is for you to understand the isset and the variable $_SESSION. I will reinforce: ... [read next comment]

  • continuation]... isset($_SESSION) has no logic/need - if (isset($id)) { has no logic/need. One more tip, remove session_start from within the functions and put it at the top of the help.php file and move the line <?php &#xA; include 'scripts/help.php';&#xA;?> before DOCTYPE. This will probably solve part of the problem.

Show 2 more comments

1 answer

4


First of all, always remember to post as many details as possible, for example:

  • The important code snippets
  • How your code should work and how it’s working
  • The mistakes occurred (not something like: did not work, gave dick, nothing happens)
  • Any dependency and/or lib you use and find relevant

Answer

In a nutshell the solution to your problem is to log in at the beginning of every file and/or layout you have, or in this case at least on index php..

But for a better understanding, I ask you to look at the topics below:

session_start( );

Log in at the beginning of every file, and not just at your function. This way you can access the session items anyway, and not only within your function where you were starting the session.

So your code would look 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'])) {

php validation.:

<?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]

As with the @Guilherme-nascimento also mentioned, withdraw the session_start() from inside your file help.php and just leave it on index.php and in the validation.php.

The archive help.php until then it is used only to maintain its useful functions, and as it is included in the index.php the session is shared.

isset( )

Also as mentioned by @Guilherme-nascimento, there is no need for you to check the existence of $_SESSION, aiming that you have already "startou/initiated" her.

Therefore, you should check only if the Dice/key/key/value that you wish to exist in the session, ie:

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

I hope I’ve helped.

Any questions, leave a comment below.

  • Just a few more details if you would like to add the answer: http://answall.com/questions/68757/erro-ao-testar-uma-sessao#comment140411_68757 (note that the author’s "code" problem goes beyond this)

  • @Guilhermenascimento added :)

Browser other questions tagged

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