This tutorial tackles how to create a login page using Angular JS and set SESSION with PHP/MySQLi. Angular JS is a javascript framework maintained by Google and is capable of creating Single-Page Applications. In this tutorial, we'll set up PHP Session to prevent users from going into our homepage if not authenticated.
Getting Started
I've have used CDN for following :
- Boostrap
- Angular JS
- Angular Route
Since I have used CDN's for the plugins/libraries/frameworks, this means you will be needing an internet connection in order to work the scripts below properly.
Creating our Database
First, we are going to create our database and insert sample users to test our app.
- Open phpMyAdmin.
- Click databases, create a database and name it as angular.
- After creating a database, click the SQL and paste the below codes. See the image below for detailed instruction.
INSERT INTO `members` (`memid`, `username`, `password`, `firstname`, `lastname`, `address`) VALUES
(1, 'neovic', 'devierte', 'Neovic', 'Devierte', 'Silay City'),
(2, 'julyn', 'divinagracia', 'Julyn', 'Divinagracia', 'E.B. Magalona'),
(3, 'gemalyn', 'cepe', 'Gemalyn', 'Cepe', 'Bohol');
You can then use the ff login details:
Username: neovic
Password: devierte
Username: gemalyn
Password: cepe
Username: julyn
Password: divinagracia
index.html
This is the main page of our app.
<!DOCTYPE html>
<title>AngularJS Login with Session using PHP/MySQLi
</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<h1 class="page-header text-center">AngularJS Login with Session using PHP/MySQLi
</h1>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
login.html
This contains our login form.
<div class="col-md-4 col-md-offset-4">
<div class="login-panel panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
<form role="form" name="logform">
<input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
<input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
<button type="button" id="loginbutton" class="btn btn-lg btn-primary btn-block" ng-disabled="logform.$invalid" ng-click="login(user)"><span class="glyphicon glyphicon-log-in"></span> <span id="logtext">Login
</span></button>
<div class="alert alert-danger text-center" ng-show="errorLogin">
<button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">×</span></button>
{{ errorMsg }}
home.html
This is our homepage after a successful login.
<div class="col-md-4 col-md-offset-4">
<h2>Welcome to Homepage
</h2>
<p>Firstname: {{ user.firstname }}
</p>
<p>Lastname: {{ user.lastname }}
</p>
<p>Address: {{ user.address }}
</p>
<p>Username: {{ user.username }}
</p>
<p>Password: {{ user.password }}
</p>
<a href="" class="btn btn-danger" ng-click="logout()"><span class="glyphicon glyphicon-log-out"></span> Logout
</a>
angular.js
This is the main Angular js of our app.
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'login.html',
controller: 'loginCtrl'
})
.when('/home', {
templateUrl: 'home.html',
controller: 'homeCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.run(function($rootScope, $location, loginService){
//prevent going to homepage if not loggedin
var routePermit = ['/home'];
$rootScope.$on('$routeChangeStart', function(){
if(routePermit.indexOf($location.path()) !=-1){
var connected = loginService.islogged();
connected.then(function(response){
if(!response.data){
$location.path('/');
}
});
}
});
//prevent going back to login page if session is set
var sessionStarted = ['/'];
$rootScope.$on('$routeChangeStart', function(){
if(sessionStarted.indexOf($location.path()) !=-1){
var cantgoback = loginService.islogged();
cantgoback.then(function(response){
if(response.data){
$location.path('/home');
}
});
}
});
});
loginCtrl.js
This contains our angular controller for login.html.
'use strict';
app.controller('loginCtrl', function($scope, loginService){
$scope.errorLogin = false;
$scope.login = function(user){
loginService.login(user, $scope);
}
$scope.clearMsg = function(){
$scope.errorLogin = false;
}
});
homeCtrl.js
This is our angular controller for home.html.
'use strict';
app.controller('homeCtrl', ['$scope', 'loginService', function($scope, loginService){
//logout
$scope.logout = function(){
loginService.logout();
}
//fetch login user
var userrequest = loginService.fetchuser();
userrequest.then(function(response){
$scope.user = response.data[0];
});
}]);
loginService.js
This is our angular service for our login.
'use strict';
app.factory('loginService', function($http, $location, sessionService){
return{
login: function(user, $scope){
var validate = $http.post('login.php', user);
validate.then(function(response){
var uid = response.data.user;
if(uid){
sessionService.set('user',uid);
$location.path('/home');
}
else{
$scope.successLogin = false;
$scope.errorLogin = true;
$scope.errorMsg = response.data.message;
}
});
},
logout: function(){
sessionService.destroy('user');
$location.path('/');
},
islogged: function(){
var checkSession = $http.post('session.php');
return checkSession;
},
fetchuser: function(){
var user = $http.get('fetch.php');
return user;
}
}
});
sessionService.js
This is our angular service that handles our session.
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set: function(key, value){
return sessionStorage.setItem(key, value);
},
get: function(key){
return sessionStorage.getItem(key);
},
destroy: function(key){
$http.post('logout.php');
return sessionStorage.removeItem(key);
}
};
}]);
login.php
This is our PHP code for login.
<?php
$conn = new mysqli("localhost", "root", "", "angular");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$out = array('error' => false);
$username = $user->username;
$password = $user->password;
$sql = "SELECT * FROM members WHERE username='$username' AND password='$password'";
$query = $conn->query($sql);
if($query->num_rows>0){
$row = $query->fetch_array();
$out['message'] = 'Login Successful';
$out['user'] = uniqid('ang_');
$_SESSION['user'] = $row['memid'];
}
else{
$out['error'] = true;
$out['message'] = 'Invalid Login';
}
?>
session.php
This is our PHP code is checking if the session has been set.
<?php
if(isset($_SESSION['user'])){
echo 'authentified';
}
?>
fetch.php
This is our PHP code in fetching the details of the logged-in user.
<?php
$conn = new mysqli("localhost", "root", "", "angular");
$sql = "SELECT * FROM members WHERE memid = '".$_SESSION['user']."'";
$query=$conn->query($sql);
while($row=$query->fetch_array()){
$output[] = $row;
}
?>
logout.php
Lastly, this is our PHP code in destroying our current PHP Session.
That ends this tutorial.
Happy Coding :)