DEV Community


Login best practices

tmblog profile image tmblog ・1 min read

Wanting a bit of advice regarding logging in using php and mysql.

The general flow is after validating data etc:

SELECT username, password FROM users WHERE username = $_POST['username'];

Then using password_verify() to check if the hashes match.

The question is if it is better to just query for the username first e.g.

SELECT username FROM users WHERE username = $_POST['username'];

If that yields a result then:

SELECT password FROM users WHERE username = $_POST['username'];

followed by:

password_verify($_POST['password'], $passwordFromDatabase);

Is this a better more secure approach? At least on the face of it, it looks like the password isn't exposed if username isn't correct. Any suggestions on best practices and which is a better/different approach(es) would be highly appreciated!


Editor guide
intricatecloud profile image
Danny Perez

If you're building this to learn about authentication/authorization

  • Always sanitize any user input when making a database query. There's a potential for SQL injection, you should "escape" any user input before using it in your query. See the mysql docs here

  • Don't save passwords in your database as plain-text. You can save a hash of the password, but not the actual password.

  • Do the query in one go, no added safety or performance by doing it in 2.

If you're building this for real use, the most secure approach is to not build it yourself. Use something like Firebase Auth (they have a Free Tier), or Auth0 to manage your users. The devil is in the details when it comes to managing users and their passwords, so its best to leave that to the pros and focus on building the rest of your app.

tmblog profile image
tmblog Author

That's top advice, I will certainly look into Auth0 and FB Auth. Do either allow users to register with their own emails and passwords? Is it quite easy to maintain state locally? Like sessions, remember me, etc.


intricatecloud profile image
Danny Perez

That's what they excel at, you can even configure MFA, reset passwords, confirm emails without having to code much of it yourself.

Thread Thread
tmblog profile image
tmblog Author

I'll certainly check it out.

kamiltekiela profile image
Kamil Tekiela

Never escape data going to SQL. Instead use parameterized prepared statements. Escaping is not safe and is a relic of PHP from 20 years ago.