Angular JS Login with Session using PHP/MySQLi Tutorial

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.

  1. Open phpMyAdmin.
  2. Click databases, create a database and name it as angular.
  3. After creating a database, click the SQL and paste the below codes. See the image below for detailed instruction.
  1. CREATE TABLE `members` (
  2.   `memid` int(11) NOT NULL AUTO_INCREMENT,
  3.   `username` varchar(30) NOT NULL,
  4.   `password` varchar(30) NOT NULL,
  5.   `firstname` varchar(30) NOT NULL,
  6.   `lastname` varchar(30) NOT NULL,
  7.   `address` text NOT NULL,
  8. PRIMARY KEY(`memid`)
  1. INSERT INTO `members` (`memid`, `username`, `password`, `firstname`, `lastname`, `address`) VALUES
  2. (1, 'neovic', 'devierte', 'Neovic', 'Devierte', 'Silay City'),
  3. (2, 'julyn', 'divinagracia', 'Julyn', 'Divinagracia', 'E.B. Magalona'),
  4. (3, 'gemalyn', 'cepe', 'Gemalyn', 'Cepe', 'Bohol');
database sql

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.

  1. <!DOCTYPE html>
  2. <html ng-app="app">
  3.         <title>AngularJS Login with Session using PHP/MySQLi</title>
  4.         <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  5. </head>
  6. <div class="container">
  7.   <h1 class="page-header text-center">AngularJS Login with Session using PHP/MySQLi</h1>
  8.   <div ng-view></div>
  9. </div>
  10. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  11. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
  12. <script src="js/angular.js"></script>
  13. <script src="js/controllers/loginCtrl.js"></script>
  14. <script src="js/controllers/homeCtrl.js"></script>
  15. <script src="js/services/loginService.js"></script>
  16. <script src="js/services/sessionService.js"></script>
  17. </body>
  18. </html>

login.html

This contains our login form.

  1. <div class="col-md-4 col-md-offset-4">
  2.     <div class="login-panel panel panel-primary">
  3.         <div class="panel-heading">
  4.             <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
  5.             </h3>
  6.         </div>
  7.         <div class="panel-body">
  8.                 <form role="form" name="logform">
  9.                 <fieldset>
  10.                         <div class="form-group">
  11.                         <input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
  12.                         </div>
  13.                         <div class="form-group">
  14.                         <input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
  15.                         </div>
  16.                         <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>
  17.                 </fieldset>
  18.                 </form>
  19.         </div>
  20.     </div>
  21.  
  22.     <div class="alert alert-danger text-center" ng-show="errorLogin">
  23.         <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">&times;</span></button>
  24.         {{ errorMsg }}
  25.     </div>
  26. </div>

home.html

This is our homepage after a successful login.

  1. <div class="row">
  2.         <div class="col-md-4 col-md-offset-4">
  3.                 <h2>Welcome to Homepage </h2>
  4.                 <h4>User Info:</h4>
  5.                 <p>Firstname: {{ user.firstname }}</p>
  6.                 <p>Lastname: {{ user.lastname }}</p>
  7.                 <p>Address: {{ user.address }}</p>
  8.                 <p>Username: {{ user.username }}</p>
  9.                 <p>Password: {{ user.password }}</p>
  10.                 <a href="" class="btn btn-danger" ng-click="logout()"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
  11.         </div>
  12. </div>

angular.js

This is the main Angular js of our app.

  1. var app = angular.module('app', ['ngRoute']);
  2.  
  3. app.config(function($routeProvider){
  4.         $routeProvider
  5.         .when('/', {
  6.                 templateUrl: 'login.html',
  7.                 controller: 'loginCtrl'
  8.         })
  9.         .when('/home', {
  10.                 templateUrl: 'home.html',
  11.                 controller: 'homeCtrl'
  12.         })
  13.         .otherwise({
  14.                 redirectTo: '/'
  15.         });
  16. });
  17.  
  18. app.run(function($rootScope, $location, loginService){
  19.         //prevent going to homepage if not loggedin
  20.         var routePermit = ['/home'];
  21.         $rootScope.$on('$routeChangeStart', function(){
  22.                 if(routePermit.indexOf($location.path()) !=-1){
  23.                         var connected = loginService.islogged();
  24.                         connected.then(function(response){
  25.                                 if(!response.data){
  26.                                         $location.path('/');
  27.                                 }
  28.                         });
  29.                        
  30.                 }
  31.         });
  32.         //prevent going back to login page if session is set
  33.         var sessionStarted = ['/'];
  34.         $rootScope.$on('$routeChangeStart', function(){
  35.                 if(sessionStarted.indexOf($location.path()) !=-1){
  36.                         var cantgoback = loginService.islogged();
  37.                         cantgoback.then(function(response){
  38.                                 if(response.data){
  39.                                         $location.path('/home');
  40.                                 }
  41.                         });
  42.                 }
  43.         });
  44. });

loginCtrl.js

This contains our angular controller for login.html.

  1. 'use strict';
  2.  
  3. app.controller('loginCtrl', function($scope, loginService){
  4.         $scope.errorLogin = false;
  5.        
  6.         $scope.login = function(user){
  7.                 loginService.login(user, $scope);
  8.         }
  9.  
  10.         $scope.clearMsg = function(){
  11.                 $scope.errorLogin = false;
  12.         }
  13. });

homeCtrl.js

This is our angular controller for home.html.

  1. 'use strict';
  2.  
  3. app.controller('homeCtrl', ['$scope', 'loginService', function($scope, loginService){
  4.         //logout
  5.         $scope.logout = function(){
  6.                 loginService.logout();
  7.         }
  8.        
  9.         //fetch login user
  10.         var userrequest = loginService.fetchuser();
  11.         userrequest.then(function(response){
  12.                 $scope.user = response.data[0];
  13.         });
  14.  
  15. }]);

loginService.js

This is our angular service for our login.

  1. 'use strict';
  2.  
  3. app.factory('loginService', function($http, $location, sessionService){
  4.         return{
  5.                 login: function(user, $scope){
  6.                         var validate = $http.post('login.php', user);
  7.                         validate.then(function(response){
  8.                                 var uid = response.data.user;
  9.                                 if(uid){
  10.                                         sessionService.set('user',uid);
  11.                                         $location.path('/home');
  12.                                 }
  13.                                
  14.                                 else{
  15.                                         $scope.successLogin = false;
  16.                                         $scope.errorLogin = true;
  17.                                         $scope.errorMsg = response.data.message;
  18.                                 }
  19.                         });
  20.                 },
  21.                 logout: function(){
  22.                         sessionService.destroy('user');
  23.                         $location.path('/');
  24.                 },
  25.                 islogged: function(){
  26.                         var checkSession = $http.post('session.php');
  27.                         return checkSession;
  28.                 },
  29.                 fetchuser: function(){
  30.                         var user = $http.get('fetch.php');
  31.                         return user;
  32.                 }
  33.         }
  34. });

sessionService.js

This is our angular service that handles our session.

  1. 'use strict';
  2.  
  3. app.factory('sessionService', ['$http', function($http){
  4.         return{
  5.                 set: function(key, value){
  6.                         return sessionStorage.setItem(key, value);
  7.                 },
  8.                 get: function(key){
  9.                         return sessionStorage.getItem(key);
  10.                 },
  11.                 destroy: function(key){
  12.                         $http.post('logout.php');
  13.                         return sessionStorage.removeItem(key);
  14.                 }
  15.         };
  16. }]);

login.php

This is our PHP code for login.

  1. <?php
  2.  
  3.        
  4. $conn = new mysqli("localhost", "root", "", "angular");
  5.  
  6. if ($conn->connect_error) {
  7.     die("Connection failed: " . $conn->connect_error);
  8. }
  9.  
  10. $out = array('error' => false);
  11.  
  12. $user = json_decode(file_get_contents('php://input'));
  13.  
  14. $username = $user->username;
  15. $password = $user->password;
  16.  
  17. $sql = "SELECT * FROM members WHERE username='$username' AND password='$password'";
  18. $query = $conn->query($sql);
  19.  
  20. if($query->num_rows>0){
  21.         $row = $query->fetch_array();
  22.         $out['message'] = 'Login Successful';
  23.         $out['user'] = uniqid('ang_');
  24.         $_SESSION['user'] = $row['memid'];
  25. }
  26. else{
  27.         $out['error'] = true;
  28.         $out['message'] = 'Invalid Login';
  29. }
  30.  
  31. echo json_encode($out);
  32.  
  33. ?>

session.php

This is our PHP code is checking if the session has been set.

  1. <?php
  2.         session_start();
  3.         if(isset($_SESSION['user'])){
  4.                 echo 'authentified';
  5.         }
  6. ?>

fetch.php

This is our PHP code in fetching the details of the logged-in user.

  1. <?php
  2.         session_start();
  3.  
  4.         $conn = new mysqli("localhost", "root", "", "angular");
  5.  
  6.         $output = array();
  7.         $sql = "SELECT * FROM members WHERE memid = '".$_SESSION['user']."'";
  8.         $query=$conn->query($sql);
  9.         while($row=$query->fetch_array()){
  10.                 $output[] = $row;
  11.         }
  12.  
  13.         echo json_encode($output);
  14. ?>

logout.php

Lastly, this is our PHP code in destroying our current PHP Session.

  1. <?php
  2.         session_start();
  3.         session_destroy();
  4.         session_commit();
  5. ?>

That ends this tutorial.

Happy Coding :)

Comments

I used this code. I wanted to list my data in another table. For this purpose I added code. But I did not succeed fully. I added 'controller' and 'service'. The 'datalist.js' code looks like this (the result is NOT obtained with this code.): 'use strict'; app.controller('datalist', ['$scope', 'listServices', function($scope, listServices){ var listeistek = listServices.listele(); listeistek.then(function(response){ $scope.listem = response.data ; }); }]); Alternative codes for 'datalist.js' are (the result is obtained with this code): 'use strict'; app.controller('datalist', ['$scope', 'listServices', function($scope, listServices){ var listeistek = listServices.listele(); listeistek.then(function(response){ $scope.listem = response.data[0] ; //only one record fetch }); }]); The 'listServices.js' code looks like this: 'use strict'; app.factory('listServices', function($http, $location, sessionService){ return{ listele: function(){ var datalistem = $http.get('fetchListe.php'); return datalistem; } } }); The 'fetchListe.php' code looks like this: $row['ID'], "AH_ID"=>$row['AH_ID'], "TARIH"=>$row['TARIH'], "HASTA_ID"=>$row['HASTA_ID'], "AD"=>$row['AD'], "SOYAD"=>$row['SOYAD'], "YAS"=>$row['YAS'],"AHX"=>$row['AHX']); } echo json_encode($data); ?> The result of the 'fetchListe.php' file is:
[{"ID":"1","AH_ID":"MEMIS KEDICI","TARIH":"16:56:24","HASTA_ID":"1575922","AD":"MIRAC","SOYAD":"SAHIN","YAS":"8","AHX":"MEMIS KEDICI"},{"ID":"2","AH_ID":"MEMIS KEDICI","TARIH":"16:56:10","HASTA_ID":"1192888","AD":"MUHAMMET","SOYAD":"SAHIN","YAS":"11","AHX":"MEMIS KEDICI"}, {"ID":"3","AH_ID":"MEMIS KEDICI","TARIH":"16:27:34","HASTA_ID":"1763536","AD":"MUAMMER","SOYAD":"GUMUS","YAS":"67","AHX":"MEMIS KEDICI"}]
The 'angular.js' code looks like this: var app = angular.module('app', ['ngRoute']); app.config(function($routeProvider){ $routeProvider .when('/', { templateUrl: 'login.html', controller: 'loginCtrl' }) .when('/home', { templateUrl: 'home.html', controller: 'homeCtrl' }) .when('/listele', { templateUrl: 'listele.html', controller: 'datalist' }) .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 sessino 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'); } }); } }); }); The 'listele.html' code looks like this:

listele .html

ID: {{ listem.ID }}

AD: {{ listem.AD }}

SOYAD: {{ listem.SOYAD }}

YAS: {{ listem.YAS }}

TARİH: {{ listem.TARIH }}

AİLE HEKİMİ: {{ listem.AHX }}

Exit {{c.ID}} {{c.AD}} {{c.SOYAD}} {{c.TARIH}}\ {{c.YAS}}
I've got 'one record' successfully. But I have not been able to list all the data with 'ng-repeat'! Where did I make a mistake?

In reply to by kanber

wrong layout, you lost the table tag in template: 'listele.html'

Add new comment