-5

I have this PHP login code (that I borrowed from another question on here) - I am easily able to hack it with SQL injection and would like to make it more secure - bit of a newbie to development and would like some assistance! How do I stop these kind of attacks? Thank you!

$userinfo = array(
                'user1'=>'password1',
                'user2'=>'password2'
                );

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($userinfo[$_POST['username']] == $_POST['password']) {
        $_SESSION['username'] = $_POST['username'];

    }else {
        //Invalid Login
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Login</title>
    </head>
    <body>
        <?php if($_SESSION['username']): ?>
            <p>You are logged in as <?=$_SESSION['username']?></p>
            <p><a href="?logout=1">Logout</a></p>
        <?php endif; ?>
        <form name="login" action="" method="post">
            Username:  <input type="text" name="username" value="" /><br />
            Password:  <input type="password" name="password" value="" /><br />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

1 Answers1

1

Some hint questions for the code above

What does this return, if you have something in $_POST['username'] that is not a key in the array?

$userinfo[$_POST['username']] 

What does this return, if you don't specify any password in the POST request?

$_POST['password']

Hint: they are the same, whatever they are...

And to clarify: this is not SQL injection. Just plain exploiting a dumb program.

ppeterka
  • 20,583
  • 6
  • 63
  • 78