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
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.
1 2 3 4 5 6 7 8 9 |
CREATE TABLE `members` ( `memid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) NOT NULL, `password` varchar(30) NOT NULL, `firstname` varchar(30) NOT NULL, `lastname` varchar(30) NOT NULL, `address` text NOT NULL, PRIMARY KEY(`memid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
1 2 3 4 |
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'); |
Username: neovic
Password: devierte
Username: gemalyn
Password: cepe
Username: julyn
Password: divinagracia
Index.html
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html ng-app="app"> <head> <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"> </head> <body> <div class="container"> <h1 class="page-header text-center">AngularJS Login with Session using PHP/MySQLi</h1> <div ng-view></div> </div> <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> <script src="js/angular.js"></script> <script src="js/controllers/loginCtrl.js"></script> <script src="js/controllers/homeCtrl.js"></script> <script src="js/services/loginService.js"></script> <script src="js/services/sessionService.js"></script> </body> </html> |
Login.html
html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<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 </h3> </div> <div class="panel-body"> <form role="form" name="logform"> <fieldset> <div class="form-group"> <input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required> </div> <div class="form-group"> <input class="form-control" placeholder="Password" type="password" ng-model="user.password" required> </div> <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> </fieldset> </form> </div> </div> <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 }} </div> </div> |
Home.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<div class="row"> <div class="col-md-4 col-md-offset-4"> <h2>Welcome to Homepage </h2> <h4>User Info:</h4> <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> </div> </div> |
Angular.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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 angular controller for login.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
'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
Angular controller for home.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
'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
Angular service for our login.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
'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
Angular service that handles our session.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
'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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
'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); } }; }]); |
Session.php
PHP code is checking if the session has been set.
1 2 3 4 5 6 |
<?php session_start(); if(isset($_SESSION['user'])){ echo 'authentified'; } ?> |
Fetch.php
PHP code in fetching the details of the logged-in user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php session_start(); $conn = new mysqli("localhost", "root", "", "angular"); $output = array(); $sql = "SELECT * FROM members WHERE memid = '".$_SESSION['user']."'"; $query=$conn->query($sql); while($row=$query->fetch_array()){ $output[] = $row; } echo json_encode($output); ?> |
Logout.php
Lastly, this PHP code in destroying our current PHP Session.
1 2 3 4 5 |
<?php session_start(); session_destroy(); session_commit(); ?> |