How to make a login system in PHP

How to make a login system in PHP

If you’re ever working on a project that needs a web UI to log in with, here’s how to do it securely with PHP. First of all, let me mention that this is NOT meant to be a complete tutorial, but rather some snippets to get you started. I assume no responsibility for any security holes that come from following this tutorial, however unlikely that is.

Hash, hash, hash

The most important thing when building a login system is to hash the passwords. Never store passwords in plain text, as that is just asking for a breach to happen. If your passwords are properly hashed, they will be useless to hackers who manage to get their hands on your login databse. Luckily, PHP has a built-in function to hash and salt passwords for you. All you need to do, after you get the user input, is to run:

$hash=password_hash('plaintext_pass;, PASSWORD_DEFAULT);

and put the hash variable in your DB instead of the plain text one.

Verification

If you used the PHP password_hash function, you can easily verify user passwords with the password_verify function. After you have the password the user entered, and the hash from wherever it’s stored, just use:

if(password_verify($passowrd, $hash)){
   //Put stuff here
}

and PHP will automatically get the salt, apply it, and do all the hard work for you.

Creating the login form

Always use “post” instead of “get” when creating the login form. This is because all “get” parameters are stored in the URL. While this is encrypted in HTTPS, it means that someone looking over your shoulder can see the password in the URL bar. “post” requests aren’t shown anywhere in the browser, and are therefore better for login and signup forms. Also, be sure to use “password” input fields to prevent people from seeing the password as it’s entered, and to prevent copying from the completed form. Here’s an example:

HTML:

<form action="login.php" method="post">
User: <input type="text" name="user" required>
Pass: <input type="password" name="password" required>
<input type="submit" name="submit" value="Log in">
</form>

and in “login.php”

if(!isset($_POST['submit'])){
    echo "Oops, the submit button was not pressed. Please try again.";
    exit();
}
$user=$_POST['user'];
$password=$_POST['pass'];

and you now have the username and password in a variable, which can be used in combination with password_verify to create a functional login form.

Easy way…

Or, you can just use my SQLite Login system, which just requires you to clone a file, and your login system is done! This takes care of all the hashing, verifying, and forms. This leaves you free to use the set session variables to know who logged in.

Source: Manuals for functions used on php.net

Leave a Reply(Markdown is On)

%d bloggers like this: