Creating a login system in PHP

Blimeo picture Blimeo · Jul 3, 2012 · Viewed 21.2k times · Source

Can someone please help me? My username is Blimeo and my password is "password" but when I put my credentials in, it says "Access denied" like I told it to. I am 100% sure that I configured my mySQL database correctly.

<html>
<body>
<?php
echo sha1('Blimeo');
if (isset($_REQUEST['attempt'])) {

    $link = mysql_connect('localhost', 'root', 'password') or die('Could not connect to database');
    $user = mysql_real_escape_string($_POST['user']);
    $password = sha1(mysql_real_escape_string($_POST['password']));
    mysql_select_db('test_users');
    $query = mysql_query(
        "SELECT user 
        FROM users 
        WHERE user = '$user' 
        AND password = '$password'
        ") or die(mysql_error());
    mysql_fetch_array($query);
    $total = mysql_num_rows($query);
    if ($total > 0) {
        session_start();
        $_SESSION['user'] = 'blah';
        header('location: dashboard.php');
    }
    else {
        echo '<br>Access denied!';

    }
}


?>
<form method="post" action="login.php?attempt">
    Enter your username:<input type="text" name="user"/><br/>
    Enter your password:<input type="password" name="password"/><br/>
    <input type="submit"/>
</form>
</body>
</html>

Answer

Sliq picture Sliq · Jul 3, 2012

UPDATE, 2016

Please only use existing login systems, which are provided out-of-the-box in nearly every PHP framework! There's absolutly no reason to write this by yourself, as user authentication is a big topic and it will take months (years) to write a serious, stable and modern login solution.

ORIGINAL TEXT, FROM 2012:

As login systems are a security issue and EVERYBODY makes the same mistakes over and over again, i can clearly say:

Take a professional script and work through the code to understand whats happening, what hashing and salting is and what problems session can have.

[removed outdating link]

Here are three projects that might be what you need:

https://github.com/panique/php-login-one-file

https://github.com/panique/php-login-minimal

https://github.com/panique/huge