HTML CSS JavaScript jQuery PHP MySQL

Secure Login System with PHP and MySQL

Updated on by David Adams

Secure Login System with PHP and MySQL

For this tutorial I'll be teaching you how you can create your very own secure PHP login form, a login form is what your website's visitors will use to login to your website to access content for logged-in users (such as a profile page).

The requirements you need for this tutorial are:

  • Web Server - I recommend you use XAMPP if you're developing your PHP applcations on a local computer, skip below if you've installed XAMPP.
  • PHP 5 (or over) - most servers will install the latest PHP for you when you install your web server.
  • MySQL server and the MySQLi extension for PHP (usually enabled by default).

File Structure

\-- phplogin
  |-- index.html
  |-- authenticate.php
  |-- logout.php
  |-- home.php


1. Creating the Login Form Design

The first thing we need to do is create the design for our login form, so for this part, we'll use HTML and CSS, you're free to create your own design template or copy the code below.

index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Login Form Tutorial</title>
		<style>
		.login-form {
			width: 300px;
			margin: 0 auto;
			font-family: Tahoma, Geneva, sans-serif;
		}
		.login-form h1 {
			text-align: center;
			color: #4d4d4d;
			font-size: 24px;
			padding: 20px 0 20px 0;
		}
		.login-form input[type="password"],
		.login-form input[type="text"] {
			width: 100%;
			padding: 15px;
			border: 1px solid #dddddd;
			margin-bottom: 15px;
			box-sizing:border-box;
		}
		.login-form input[type="submit"] {
			width: 100%;
			padding: 15px;
			background-color: #535b63;
			border: 0;
			box-sizing: border-box;
			cursor: pointer;
			font-weight: bold;
			color: #ffffff;
		}
		</style>
	</head>
	<body>
		<div class="login-form">
			<h1>Login Form</h1>
			<form action="authenticate.php" method="post">
				<input type="text" name="username" placeholder="Username">
				<input type="password" name="password" placeholder="Password">
				<input type="submit">
			</form>
		</div>
	</body>
</html>

When we load up our index.html file our login form will look like this:

CSS3 HTML5 Secure Login Form Design

The form has its request method set to post, this will send the username and password to the server when the user clicks the submit button, we can then handle the sent data with PHP.

Handling the sent data will be done in our authenticate.php script.


2. Creating the Accounts Database

For this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred MySQL database management application.

Go ahead and create a new database, you may use any name, for this tutorial I will name the database phplogin and use the collation utf8_general_ci.

What we need now is an accounts table, this table will store all the accounts (usernames, passwords, emails, etc), while you have your database open execute the below SQL statement.

If you're are using phpMyAdmin, click your database on the left side panel and click the SQL tab at the top.

SQL Statement

CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', '$1$zlnYwMy4$XJXe7it14YoWwr0lrK3M4.', 'test@test.com');

ALTER TABLE `accounts` ADD PRIMARY KEY (`id`);
ALTER TABLE `accounts` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

On phpMyAdmin this should look like:

CSS3 HTML5 Secure Login Form Design

The above SQL statement code will create the accounts table with the columns id, username, password, and email.

We also insert a test account with the username test, you don't really need this account, it's just for testing purpose to make sure our login works correctly.


3. Authenticating Users with PHP

Now we need to handle our requests that are sent from index.html, for this we need to use PHP, PHP is a popular server-side language that can access our MySQL database.

I have commented on different parts of the script so you can understand what each part does.

authenticate.php

<?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
	// If there is an error with the connection, stop the script and display the error.
	die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	die ('Username and/or password does not exist!');
}
// Prepare our SQL 
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
	$stmt->bind_param('s', $_POST['username']);
	$stmt->execute(); 
	$stmt->store_result(); 
	// Store the result so we can check if the account exists in the database.
	if ($stmt->num_rows > 0) {
		$stmt->bind_result($id, $password);
		$stmt->fetch();      
		// Account exists, now we verify the password.
		if (password_verify($_POST['password'], $password)) {
			// Verification success! User has loggedin!
			$_SESSION['loggedin'] = TRUE;
			$_SESSION['name'] = $_POST['username'];
			$_SESSION['id'] = $id;
			echo 'Welcome ' . $_SESSION['name'] . '!';
		} else {
			echo 'Incorrect username and/or password!';
		}
	} else {
		echo 'Incorrect username and/or password!';
	}
	$stmt->close();
} else {
	echo 'Could not prepare statement!';
}
?>

The above PHP script will connect to our database "phplogin" and check to see if the user has sent the correct information to the server, the passwords are created using PHP's password_hash and then checked with password_verify, you may remove this but for security reasons it's best to keep it (helps prevent account passwords from being exposed).

After the user has been verified, we can create PHP sessions, the sessions can check to see if the user is logged-in as they are shared across your PHP scripts, just remember to start your PHP script with session_start.

Sessions act as cookies that will remember information, but will not be stored on the visitor's computer, the server will remember the sessions that you create because it temporarily stores them on the server.

If everything has been set-up correctly, you can go ahead and login with the username test and password test, if successful you should be shown a welcome message that will display your username.

You need to use the password_hash function in your registration system, the script will return an invalid credentials error if you do not, if you do not want the added security, you can replace this line of code:

if (password_verify($_POST['password'], $password)) {

With:

if ($_POST['password'] == $password) {

4. Creating the Logout Script

For a visitor to log out, all we need to do is create a new file and destroy the sessions that are created when the user successfully logs in.

logout.php

<?php
session_start();
session_destroy();
header('Location: index.html');
?>

5. Creating the Home Page for Logged-in Users

Now we can interact with our logged-in users.

home.php

<?php
// check to see if the user is logged in
if ($_SESSION['loggedin']) {
	// user is logged in
	echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
	// user is not logged in, send the user to the login page
	header('Location: index.html');
}
?>


Conclusion

You should now have a basic understanding of how a login system works with PHP and MySQL, you're free to copy the source code and use it in your own projects. The next step is to create a registration system that will allow the visitors to register.

Don't forget to follow us and share the article if you find it useful, this will help us create future tutorials.

Next tutorial in this series: Secure Registration System with PHP and MySQL


Download Source