Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Henrik Christensen
seal-mask
.a{fill-rule:evenodd;}techdegree
Henrik Christensen
Python Web Development Techdegree Student 38,322 Points

secure enough?

Hi,

I've been trying to create a login using PDO and MySQL, but I have had problems making it work for a couple days now :-/

I thought I could use something like rowCount() or fetchColumn() to see if there is a user with a username and password equal to the entered informations, but rowCount() returned 1 even with incorrect usernames (found out it's not working with SELECT statements) and fetchColumn() just returned string(1) "0" no matter if the informations was correct or incorrect :-/

Now I made it work by searching for a user with the username entered -> if there is then store user-info in a variable named i.e. $user -> then password_verify() the entered password with the hashed password stored in the db -> if everything is correct then log in the user.

Now I'm wondering if it is secure enough to store the user information in a variable?

login.php

<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING));
    $password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING));

    if (empty($username) || empty($password)) {
        $message = 'Please fill out both fields';
    }

    if (!empty($username) && !empty($password)) {
        require(__DIR__ . '/inc/query_functions.php');
        // $_SESSION['login'] = true;
        // header("location:admin.php");
        // die();

        $user = select_single_user($username);

        if (!empty($user)) {
            if (password_verify($password, $user['psword'])) {
                die('Logged in!');
            } else {
                $message = 'Incorrect informations';
            }
        } else {
            $message = 'Incorrect informations';
        }
    }
}