Rita Soares
Rita Soares

Reputation: 31

php session error to logout

My login is working, since its redirecting me to the index.php.
But after I click on the login button it goes to the index.php, and the session is not logged in. It's supposed to state "Hello $username", but it still states "Login again" instead of Logout.

index.php code:

<?php
        session_start();    
        if( !empty($_SESSION) && isset($_SESSION['username'])){
            echo 'Olá ' . $_SESSION['username'];
            echo '<a href="logout.php"><br/>Logout</a>';
        }
        else{
            echo '<a href="login.php" class="hiper">Fazer Login</a>';
            echo '<a href="criarconta.php" class="hiper"><br/>Criar Conta</a><br/>';
        }
      ?>

login.php code:

<?php

    if(!empty($_POST)){
        $username=$_POST['username'];
        $password=$_POST['password'];

        require_once 'Validate.php';
        $flag_error = false;
        $errors = array ('username' => array (false,'username incorrecto.'),'password' => array (false,'Password tem de conter pelo menos 8 caracteres.'));


    /*if(!checkusername($username)){
        $errors['username'][0] = true;
        $flag_error=true;

    }

    if(!Valid_Pass($password)){
        $errors['password'][0]=true;
        $flag_error=true;

    }*/

    if(!$flag_error){

        require_once 'ligacao.php';
        $query = "SELECT * FROM utilizadores` WHERE 'username' = '$username' AND 'password' = '$password'";
        $verificar=mysql_query($query) or die (mysql_error());

        if (mysql_num_rows($verificar)==true){
            $_SESSION['username'] = $username;
            header('Location: index.php');
            }else{
            echo '<font color="red"> Esta conta não existe. </font></a>';   
        }

    }   
}
?>

I know login works because it redirects to "header('Location: index.php');", but the session stay logged in. What could it be?

Upvotes: 3

Views: 136

Answers (2)

user3994255
user3994255

Reputation:

session_start();

This starts the session and you should use it in every file who you need to user Login for visit it.

 $_SESSION['color']='red'; 
 $_SESSION['size']='small'; 
 $_SESSION['shape']='round';

This sets variables in the session

 session_unset();

Remove all session variables

 session_destroy(); 

Destroy the session

Upvotes: 0

jdmcguire
jdmcguire

Reputation: 111

You need to use session_start() on every page that uses the session, so add it to the top of login.php.

Upvotes: 3

Related Questions