Jun 26 2017
Jun 26, 2017

How to build a Login form using PHP (PDO) and AJAX

Categorised in:

Hello, everybody! Today we will talk about Login Forms for a website using PHP and AJAX. We will build a filter to secure the information from our form. Before we start, I want to let you know that this tutorial requires basic knowledge of HTML, CSS, PHP and JavaScript.

The first step will be to create a table in MySQL which will contain 4 columns: id, nickname, password and session. Here you have the SQL code to create a user table:

CREATE TABLE users (
    id int,
    nickname varchar(50),
    password varchar(100),
    session varchar(255),
    PRIMARY KEY (id)
);

If you use XAMPP you can find your phpMyAdmin using this link: http://localhost/phpmyadmin

Insert a new user using this SQL code:

INSERT INTO users (id, nickname, password)
VALUES (1, 'admin', 'admin123');

Now we need to create a config.php file and write there the connection to the data base. Let’s save it in public_html or if you work on a local server using XAMPP just save your file in htdocs folder. Paste there the following code:

<?php
class Connect extends PDO
{
    public function __construct()
    {
        parent::__construct("mysql:host=localhost;dbname=yourdatabase", 'dbuser', 'userpassword',
		array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        $this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }
}
?>

Replace yourdatabase with the name of your database, dbuser with database’s user and the userpassword with your user’s password. Save the file.

Now, let’s create a folder in public_html or htdocs and name it css and in this folder we will create another file which is style.css. In this file we should write this code:

#login_form{
	width: 20%;
	margin: 100px auto;
	padding: 10px;
	background: #dddddd;
	border-radius: 5px;
	border: 1px solid #444;
	background: #009688;
}
input[type="text"], 
input[type="email"], 
input[type="password"], 
input[type="file"], 
select{
	background-color: #fff;
	box-sizing: border-box;
	border-radius: 2px;
	color: #333;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	float: none;
	font-size: 16px;
	border: 1px solid #ccc;
	padding: 6px 10px;
	height: 38px;
	width: 100%;
	line-height: 1.3;
	margin-bottom: 10px;
}
textarea{
	background-color: #fff;
	box-sizing: border-box;
	border-radius: 2px;
	color: #333;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	float: none;
	font-size: 16px;
	border: 1px solid #ccc;
	padding: 6px 10px;
	width: 100%;
	line-height: 1.3;
}
input[type="submit"]{
	margin-top: 10px;
	background-color: #eee;
	border: 1px solid #ddd;
	color: #333;
	font-size: 1em;
	padding: 10px 15px;
	cursor: pointer;
}
input[type="submit"]:hover{
	margin-top: 10px;
	background-color: #ddd;
	border: 1px solid #ddd;
	color: #333;
	font-size: 1em;
	padding: 10px 15px;
}

This is a CSS code and we will include this file in our main file in the next steps.

After we are done with our CSS file we need to create another folder and name it js and create in that folder a new js file like this: /js/script.js Write the following code and pay attention to the comments I wrote there for you so you can understand how it works.

$(document).ready(function() {
	// here we get our form id from index.php 
	// (<form id="login" action="" method="POST">)
	var login = $('#login');
	// here we get the div class from index.php
	// in this div the AJAX will output the response which mens
	// that will show there the result from /ajax/login.php
	var alert_content = $('.alert_content');
	login.on('submit', function(e) {
		e.preventDefault();
		// here is our ajax function wich looks like this:
		$.ajax({
			// here is the location to our php file which will be called by AJAX
			url: '../ajax/login.php',
			// the data will be sent using POST method
			type: 'POST',
			// data type is HTML
			dataType: 'html',
			data: login.serialize(),
			// so here before we get any response from it is going to show "Loading..."
			beforeSend: function() {
				alert_content.fadeOut();
				alert_content.fadeIn();
				alert_content.html('Loading...');
			},
			// if the data was successfully sent
			// then it shouw the result in our "alert_content" div
			success: function(data) {
				alert_content.html(data).fadeIn();
				login.trigger('reset');
			},
			error: function(e) {
				console.log(e)
			}
		});
	});
});

We also need the jquery library and we can get it from this link: https://jquery.com/download/

After we download it from there we should save it in our /js/ folder.

 

The next file is index.php which will be saved also in public_html or if you use XAMPP save it in your htdocs folder with the following code:

<?php
// call here our file with MySQL connection 
// so we can use it in index.php
require_once('config.php');
?>
<!doctype html>
<html lang="en-US" prefix="og: http://ogp.me/ns#" class="no-js">
<head>
	<title>
		Login form
	</title>
	<script type='text/javascript' src='js/jquery-3.2.1.min.js'></script>
	<script type='text/javascript' src='js/script.js'></script>
	<link rel='stylesheet' href='css/style.css' />
</head>
<body>
	<div id="login_form">
		<!-- This is the div where AJAX will send the response -->
		<div class="alert_content"></div>
		<form id="login" action="" method="POST">
			<input type="text" name="nickname" placeholder="Nickname" />
			<input type="password" name="password" placeholder="Password" />
			<input type="submit" value="Enter" />
		</form>
	</div>
</body>
</html>

As you saw in our AJAX function from script.js we have to create another folder /ajax/ with a new php file named login.php. => /ajax/login.php In this file we will write our php function which will check the information from our Login form and in case there is such a user it will show us the user’s nickname and also it will save a cod (session) in user table in session column. Otherwise, it means there is no user with such nickname and password and our script will tell us that the nickname or password is incorrect.

login.php will look like this:

<?php
// we call our file with MySQL connection
require_once('../config.php');
// create a new Object
class User{
	// filter the information from Login form.
	function filter($str){
		//convert case to lower
		$str = strtolower($str);
		//remove special characters
		$str = preg_replace('/[^a-zA-Z0-9]/i',' ', $str);
		//remove white space characters from both side
		$str = trim($str);
		return $str;
	}
	// the function for checking date
	function check_user($nickname,$password){
		$db = new Connection;
		$nickname = $this -> filter($nickname);
		$user = $db -> prepare("SELECT id FROM users WHERE nickname = :nick AND password = :pass");
		$user -> execute(array(
			'nick' => $nickname,
			'pass' => $password
		));
		if($user -> rowCount() > 0){
			$con = 'Welcome ' .$nickname.'!';
		}else{
			$con = 'The nickname or password is incorrect!';
		}
		return $con;
	}
}

$User = new User;

echo $User -> check_user($_POST['nickname'],$_POST['password']);
?>

We will use the session in our next tutorial where we will talk about cookies and other stuff you need to know about the User Login System.

Thank you!

Find this tutorial on youtube.