Set up PHP Local Environment
In this tutorial, we are going to build a simple login system in PHP. We will use AJAX to send data to the back-end and then receive back a JSON response. Let’s get into it. First, make sure you have an Apache server running, or if you like to use nginx, you may do so. For beginner, I would recommend you to use XAMPP instead. XAMPP comes with both Apache and Mysql which we will use in this tutorial.
IDE – Integrated Development Environment
Now, way long before, developer used Notepad to code, but now we do not have to go through the hardship of using Notepad anymore. There are tons of IDE that you can use to help you to code. We will be using Visual Studio Code. You can opt for something else if you like for example, Atom, Eclipse for PHP, PhpStorm, Notepad++ just to name a few.
Setting Up Our Project Folder
Now, once you have installed XAMPP, go to your xampp/htdocs folder C:/xampp/htdocs
, this will always be the directory to your htdocs folder unless you decide to install XAMPP somewhere else.
Create a new folder and name it whatever name you like. I am going to call it phplogin
. Now open your IDE of your choice and open the directory of your project. Create a new index.php
file. Copy and paste the following code into your index.php
. The index.php
contains the HTML, PHP, and Javascript to handle user login.
<?php
@session_start();
require "header.php";
?>
<body>
<div class = 'container-fluid'>
<div class = 'text-center text-dark'>
<h2>LOGIN</h2>
</div>
<div class = 'row w-100 mt-5'>
<div class = 'offset-3 col-md-6 mt-5'>
<form id = "loginForm">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-check">
<a href = "register.php" >Don't have an account? Register here</a>
</div>
<button type="button" id = 'buttonSubmit' class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$("#buttonSubmit").click(function(){
// disable submit button
$(this).prop('disabled', true);
//check if email or password input is empty
if( $("#email").val() == '' || $("#password").val() == ''){
alert('Email or Password cannot be empty');
}else{
const email = $("#email").val();
const password = $("#password").val();
postData = {
action : 'login',
email : email,
password : password
}
$.ajax({
url: "backend.php",
type: "POST",
data: postData,
dataType: 'json'
}).then( function(result){
//const json = JSON.parse(result);
if(result.status == 1){
window.location.href = "/profile.php";
}
});
}
// enable back submit button
$(this).prop('disabled', false);
})
});
</script>
</body>
</html>
Create another file called header.php
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
Create another file called register.php
. This will contain the HTML, PHP, and Javascript to handle user registration.
<?php
@session_start();
require "header.php";
?>
<body>
<div class = 'container-fluid'>
<div class = 'text-center text-dark'>
<h2>REGISTER</h2>
</div>
<div class = 'row w-100 mt-5'>
<div class = 'offset-3 col-md-6 mt-5'>
<form>
<div class="form-group">
<label for="username">Username</label>
<input type="email" class="form-control" id="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-check">
<a href = "/" >Already have an account? Login here</a>
</div>
<button type="button" id = 'buttonSubmit' class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
<script>
$( document ).ready(function() {
$("#buttonSubmit").click(function(){
// disable submit button
$(this).prop('disabled', true);
//check if email or password input is empty
if( $("#username").val() == '' || $("#email").val() == '' || $("#password").val() == ''){
alert('Email or Password cannot be empty');
}else{
const username = $("#username").val();
const email = $("#email").val();
const password = $("#password").val();
postData = {
action : 'register',
username : username,
email : email,
password : password
}
$.ajax({
url: "backend.php",
type: "POST",
data: postData,
dataType: 'json'
}).then( function(result) {
if(result.status == 1){
window.location.href = "/profile.php";
}
});
}
// enable back submit button
$(this).prop('disabled', false);
})
});
</script>
</body>
</html>
Create another file and name it profile.php
<?php
@session_start();
require "header.php";
if( isset($_SESSION['username']) && !empty($_SESSION['username']) ){
$username = $_SESSION['username'];
}else {
header("Location: /");
}
?>
<body>
<div class = 'container-fluid'>
<div class = 'text-center text-dark'>
<h2>PROFILE</h2>
</div>
<div class = 'text-center text-dark'>
<h2>Welcome, <?php echo $username; ?></h2>
</div>
<div class = 'row w-100 mt-5'>
<button type = 'button' class = 'btn btn-outline-info' id = 'logout'>Logout</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#logout').click(function(){
const action = 'logout'
const postData = {
action : action
}
$.ajax({
url: "backend.php",
type: "POST",
data: postData,
dataType: 'json'
}).then( function(result){
//const json = JSON.parse(result);
console.log(result);
if(result.status == 1){
window.location.href = "/";
}
});
})
});
</script>
</body>
</html>
With all the 4 php files created, we will need another php file that will contain the back-end logic for login, register and logout. Create another file and name it backend.php
<?php
if( $_POST && isset($_POST) ){
if($_POST['action'] == 'login'){
login($_POST);
}elseif($_POST['action'] == 'register') {
register($_POST);
}elseif($_POST['action'] == 'logout') {
logout($_POST);
}
}
function login($input){
// localhost, username, password, db_name
$conn = mysqli_connect("localhost","root","","phplogin");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$email = $input['email'];
$password = $input['password'];
$sql = "Select * From users Where email = '$email'";
$sql = $conn->query($sql);
if($sql){
$sql = $sql->fetch_assoc();
if(password_verify($password, $sql['password'])){
@session_start();
$_SESSION['email'] = $email;
$_SESSION['username'] = $sql['username'];
echo json_encode(array("status" => 1, "message" => "Successful Login"));
return;
}else{
echo json_encode(array("status" => 0, "message" => "Login failed"));
return;
}
}else{
echo json_encode(array("status" => 0, "message" => "No email found"));
return;
}
}
function register($input){
$conn = mysqli_connect("localhost","root","","phplogin");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$username = $input['username'];
$email = $input['email'];
$password = $input['password'];
$passwordHashed = password_hash($password, PASSWORD_BCRYPT);
$username = mysqli_real_escape_string($conn, $username);
$email = mysqli_real_escape_string($conn, $email);
$passwordHashed = mysqli_real_escape_string($conn, $passwordHashed);
$sql = "Select users.username From users Where username = '$username'";
$sql = $conn->query($sql);
$sql = $sql->fetch_assoc();
if($sql){
echo json_encode( array("status" => 0, "message"=> "Username already taken"));
return;
}else{
$sql = "Insert Into users (username, email, password) VALUES ('$username', '$email', '$passwordHashed')";
$sql = $conn->query($sql);
if($sql){
@session_start();
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
echo json_encode(array("status" => 1, "message" => "Successful Registration"));
}else{
echo json_encode(array("status" => 0, "message" => "Registration failed"));
}
}
}
function logout($input){
@session_start();
session_destroy();
unset($_SESSION);
echo json_encode(array("status" => 1, "message" =>"Logout Successful"));
return;
}
?>
Now, in the backend.php
. We defined our mysqli_connect
to connect to our database. This will be different depending on your database credentials. Change the arguments accordingly. $conn = mysqli_connect("ip","username","password","db_name");
If you are using XAMPP, make sure you run the MySQL service as well and go to localhost/phpmyadmin on your browser. Create a database and create a table called users
. You may use below db script to help you create the users
table.
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
Now everything is in place. Go to localhost
and you now have a working user login system complete with a profile page.
Check out my other post on how to build a login in Angular here