使用PHP在mysql数据库中检查用户名和散列/ salted密码

When validating user logins, is it safe to first search for the username and THEN if found, retrieve the hashed password and salt and compare it with the user input?

Or, should the salt for the user-inputed username be retrieved by itself, then be hashed with the inputed password and compared with the final hash in the database?

In essence, is it safe to store a password for an inputed username from a database before knowing whether the password the user entered is valid?

You may check both loginname and password at the same time. Get the raw password; salt it, then check if salted password and username combination exist. Ofcourse, password in db should have been salted and hashed before.

 if($loginname AND $loginpass){
  $loginpass=sha1($salt1.$loginpass.$salt2,$raw_output=false );

    $userinfo_query="SELECT * FROM users WHERE user_name='$loginname' AND user_pass='$loginpass' LIMIT 1";

  }

If you look at the examples of the PHP Password Hashing API https://github.com/ircmaxell/password_compat the answer is: No, you read the user from the database and compare the stored password hash with the password you just got from the login form.

And please try to use this library - PHP 5.5 will support the functions natively, and if you are on PHP 5.3.7 and later, it sounds like a very good idea not to reinvent the wheel and simply use these functions. Doing your own thing is more likely to be attackable.