2

Is this function good for a quick login function with only one user?

function auth($post, $session)
{
    if(isset($post["username"]) && isset($post["password"]))
    {
        $session["user"] = new stdClass();
        $session["user"]->username = $post["username"];
        $session["user"]->password = $post["password"];
    }

    if(isset($session["user"]))
        if(is_object($session["user"]))
            if($session["user"]->username == "admin" && $session["user"]->password == "test")
                return true;

    return false;
}

It works but, must it be improved?

10
  • One possible improvement: you could add the user object to the session only if the login was successful. Commented Apr 3, 2012 at 1:50
  • This will definitely work but it is less than secure and would only make sense in a development/test environment. I would not put something like this on a production server. Commented Apr 3, 2012 at 1:51
  • 1
    @Joe: Why wouldn't you, though? In what way is it less than secure? (I mean, hashing and salt would be a big improvement - but it's actually better than a database for a simple single-user system.) Commented Apr 3, 2012 at 1:52
  • @Joe what's not secure about it other than having an obvious username and password? Commented Apr 3, 2012 at 1:53
  • 1
    Why go through all the rigmarole of setting array key object thingamadings if the only thing you're doing with them is test for equality? You can abbreviate this whole function down to return $post['user'] == 'admin' && $post['password'] == 'test'. Commented Apr 3, 2012 at 1:57

1 Answer 1

1

Use the session to track whether the user is logged in or not. For example, in the login page, only set the username in the session if the user authenticates properly. Logout page clears it. Then your other pages can check if the username is set in the session or not. No need to store entered password (recommend against).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.