0

When I click on Logout link it redirects to an empty page.

Here is the Login.php file:

<?php

    session_start();
    $_SESSION['logout']= 'username';

    include_once('config.php');

    if(isset($_POST['btn'])) {
        $username = addslashes($_POST['username']);
        $password = addslashes(md5($_POST['password']));

        $query = mysqli_query($connect, "SELECT * FROM register WHERE username = '$username' AND password = '$password' ")
        or die(mysql_error());
        $result = mysqli_fetch_array($query);

        if($result['username']==$username) {
            echo "You have successfully loged in <br>";
            $check = true;
        }else {
            echo "Wrong Login or Password <br>";
        }
    }

?>

<a href="logout.php">Logout</a>

Logout.php file:

<?php

    session_start();
    if(isset($_POST['logout'])) {
        session_destroy();
        header("Location:login.html");
        }
?>

Please can you correct my code and tell me what I've done wrong?

tim
  • 1,999
  • 17
  • 32
Viktor
  • 722
  • 1
  • 8
  • 25

2 Answers2

1

This line in your logout

if(isset($_POST['logout'])) {

should be using $_SESSION and not $_POST

as per

$_SESSION['logout']= 'username';

You're also mixing MySQL APIs with or die(mysql_error()) which should read as or die(mysqli_error($connect))

I noticed you are storing passwords using MD5; it's old and considered broken.

I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.

Plus, in regards to SQL injection which you are open to, use mysqli with prepared statements, or PDO with prepared statements, they're much safer.


See ircmaxell's solution to using password_hash() and PDO with prepared statements:


Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

Community
  • 1
  • 1
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

The problem is in your logout.php file, you are listening for a $_POST.

if(isset($_POST['logout'])) { ...

However, you are just using a href to link to the log out page

<a href="logout.php">Logout</a>

This means there is never going to be a $_POST['logout'] because it isn't a form (but an actual link).

Therefore as it is a link, you can just remove the if(isset($_POST['logout'])) { .. and do something like this:

<?php

session_start();
session_destroy();
header("Location:login.html");

?>
James R
  • 276
  • 5
  • 14