Hi Developers,

I'm a beginner on php/mysql and I would like some help on my LOGIN FORM. I created a database called user, table called users, and I inserted two users with two passwords. The passwords have not been encrypted yet.

hen I run my login form, If I enter a diffrent username, it'll catch that it is an incorrect username but if I entered the two usernames in the DB, there are no errors. My main problem is when I enter the password or a random password, it takes me to a blank page. It doesn't produce the echo 'Login succesfful'. It just takes me to a blank page. I hope I didn't confuse anyone. Please assist me this problem. I've been on it for a while and am not able to figure it out. Thank you.

**my Database:**
------------
CREATE DATABASE user;
USER user;
CREATE TABLE users (
id int(4) NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
PRIMARY KEY (id));

INSERT INTO users (username, password)
VALUES ('john', 'johndoe');
INSERT INTO users (username, password)
VALUES ('bill', 'clinton');


**form.php**
----------
<body>

    <form name="login" method="post" action="login.php">
        <b>Username: </b>
        <input type="text" name="username" />
        </br>
        <b>Password: </b>
        <input type="password" name="password" />
        </br>
        <input type="submit" name="submit" value="Log in"/>
    </form>
</body>
</html>

**db_connect.php**
--------------
<?php
    $username = "root";
    $password = "";

    try {
        $pdo = new PDO('mysql:dbname=user;host=localhost',$username, $password);
    } catch (PDOException $e) {
        die('ERROR: Could not connect: ' . $e->getMessage());
    }

    //Better to use PDO connection because you can easily transfer it to another DB compared to mysqli and mysql

?>

**login.php ** <--- my problem is in this file
---------
<?php
    session_start();
    include('db_connect.php');

    if(!isset($_POST['submit']))
    {
        include('form.php');
    }
    else 
    {
        $username = $_POST['username'];
        $password = $_POST['password'];

        //Check input 
        if($username == '')
        {
            die('ERROR: Please enter your username.');
        }
        if($password == '') 
        {
            die('ERROR: Please enter your password.');
        }

        //Escapes special characters in a string
        $username = mysql_real_escape_string($_POST['username']);

        //Check if username exists
        $sql = "SELECT COUNT(*) FROM users WHERE username ='$username'";
        if($result = $pdo->query($sql)) 
        {
            $row = $result->fetch();
            //if yes, fecth the encrypted password

            if($row[0] == 1) 
            {
                $sql = "SELECT password FROM users WHERE username ='$username'";

                //encrypt the password entered into the form 
                //test it against the encrypted password store in DB

                if($result = $pdo->query($sql)) 
                {
                    $row = $result->fetch();
                    $salt = $row[0];

                    if(crypt($password, $salt) == $salt)
                    {
                        echo'Login credential successful';
                    }
                    else 
                    {
                        echo'You entered an incorrect password.';
                    }
                } else {
                    echo "Error: Could not execute $sql. " . print_r($pdo->errorInfo());
                }
            } else {
                echo 'Incorrect username';
            }
        } else{
            echo "Could not execute $sql. " . print_r($pdo->errorInfo());
        }
        //close connection
        unset($pdo);        
    }
?>

Recommended Answers

All 12 Replies

Member Avatar for LastMitch

@kx220

My main problem is when I enter the password or a random password, it takes me to a blank page. It doesn't produce the echo 'Login succesfful'. It just takes me to a blank page

I'm not familiar with PDO connection. I'm more MYSQLI.

$sql = "SELECT COUNT(*) FROM users WHERE username ='$username'";

May I ask you why are you using COUNT?

Here you are using:

$sql = "SELECT password FROM users WHERE username ='$username'";

Does that make a difference? And if you were to change it to MSYQLI, how would u go on about it?

Member Avatar for diafol

1) PDO doesn't use mysql_* functions, so mysql_real_escape_string isn't right. Use a prepared statement - prepare() followed by execute() is probably the easiest way.

2) Why 2 queries? Can't you just get the pw from the first query and then check that? As LastMitch aslo notes.

3) The form looks as though it's in the same page as the form handling code - this isn't a good idea. Try separating your php and html as far as possible.

4) Try streamlining your code - many nested conditionals here - probably not req'd.

Member Avatar for diafol

I'll give an example of some old code I had knocking about - slightly modded - but NOT tested:

<?php
session_start();
include('db_connect.php');

//assume $salt1 and $salt2 included somewhere

if(!isset($_POST['submit'])){
    //deny access to direct access
    header('Location: login.php');
    exit;
}else{
    //get hold of form data
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    //Check input 
    if($username == ''){
        $error[] = 'ERROR: Please enter your username.';
    }
    if($password == ''){
        $error[] = 'ERROR: Please enter your password.';
    }
    if(strlen($password) < 8){
        $error[] = 'ERROR: Please enter a password of 8 characters or greater.';
    }

    if(!isset($error)){
        $s = $pdo->prepare("SELECT user_id, pw FROM users WHERE username = :u");
        //parameter
        $s->execute(array(':u'=>$username)); 
        //limit returned recordset to associated array
        $row = $s->fetch(PDO::FETCH_ASSOC);
        if(count($row)){
            //Use the hash or crypt of your choice
            $pw = hash('sha512', $salt1 . $password . $salt2);
            //Check hashed pw with the DB value
            if($pw == $row['pw']){
                //Success! Store the user id in a session var and redirect
                $_SESSION['user_id'] = $row['user_id'];
                header('Location: index.php');
                exit;
            }
        }
        $error[] = 'Login details incorrect'; //equally this could be a problem with the DB
    }
    //ERRORS EXIST
    //Send error messages back to login page to be listed near form - send username too so you can fill the field
    $_SESSION['login_errors'] = array('errors' => $error, 'username' => $username); 
    header('Location: login.php');
    exit;
}
?>

Ahh okay. I'll change it up abit and I'll let you guys know. Thanks.

HI, after reading through the codes you guys posted, I gained a little understanding. I did some research and found a solution for it. This is what I found.

<?php
session_start();
include('db_connect.php');

if(!isset($_POST['submit'])){
   include('form.php');
}else{
    //get hold of form data
    $username = $_POST['username'];
    $password = $_POST['password'];

    if(empty($username)){
        die('ERROR: Please enter your name');
    } if(empty($password)) {
        die('ERROR: Please enter your password');
    } 

    $sql = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :user And password =:pass");

    $params = array("user" => $username, "pass" => $password);
    $sql->execute($params);

    $status = (bool) $sql->fetchColumn(0);

    if ($status)
    {
        echo'Login successful.';

    } else {

        echo'Login fail';
    }
}
?>

This code works great. The thing is I want to learn how to catch the username/password if for example, if you enter the right username and wrong password, it'll post wrong password vice versa. I'm stuck on how to approach the $status. How would I concantinate it with the username/password to check for it? Sorry I'm asking alot of questions and researching at the same time. Thank you in advance.

if you enter the right username and wrong password, it'll post wrong password vice versa

Are you sure you want to do this? It's a potential vulnerability if an attacker can see which one was entered incorrectly.

Member Avatar for diafol

Agree with P. This is why I suggested: "Login details incorrect" and no more info than that. DO not give a potential hacker / malicious user any info that they're on the right track.

Oh good catch. Sorry I'm still a newbie and still learning. Another quick question.
I was wondering if this is the proper way to do this.

If the user successfully logged in, I want to redirect it to another page where they can upload a file to their DB. Can I just do a call on this line:

...part of the code listed above...


if ($status)
    {
        echo'Login successful.';

        //Can I insert the code here to fetch the php file
        and then call the php script???
    } 

You could do it that way using include, but you can also choose to redirect to that page using header.

Thanks so much. I didn't realize that after going through some codes and research. Not thinking straight at all. Thanks.

You are a beginner so a blank page … so why to write that page with bad practices? There are so many frameworks out there in PHP like CI or YII and of course there is there the OOP approach. PHP has a great database interface support class called PDO … why don’t you get familiar with it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.