How to write secure login scripts in PHP?

2 points by Huzi94 ↗ HN
Hello, I am an intermediate Php coder and would like to know how to write a secure login system? I use MySQL as database software and Apache as server. Help appreciated

2 comments

[ 8.9 ms ] story [ 23.8 ms ] thread
It's not like i'm going to write your login script, but I can explain you some techniques used in it.

First you have to create registration form and function to save the data into the database. Remember to check for injections and remember to hash the password.

Next you have to create login form and function to query the password with the username, then hash the password used in the login and check if the two hashes match. Then you create session cookie for the user.

This session cookie should have random hash which is regenerated always when the hash is checked ("Logged user updates the page"). Remember to check that the database does not have identical random hash when you generate new hash, if you take care of that then there wont be authentication collision happening, because this random hash will be used to "login" the user on every page after the user has logged in with his password.

Remember to store the random hash in the database and in the cookie and check that they match on every page load. If the cookie does not exist redirect the user back to login page.

Logout can just be handled by deleting the session cookie and the random hash from the database.

Wola! You have functional login script. Remember to check for injections everywhere!