Skip to main content

Angular JS Login with Session using PHP/MySQLi Tutorial

Screenshot
Body

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. <div class="form-group">
  10. <input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
  11. </div>
  12. <div class="form-group">
  13. <input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
  14. </div>
  15. <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>
  16. </form>
  17. </div>
  18. </div>
  19.  
  20. <div class="alert alert-danger text-center" ng-show="errorLogin">
  21. <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">&times;</span></button>
  22. {{ errorMsg }}
  23. </div>
  24. </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. if(isset($_SESSION['user'])){
  3. echo 'authentified';
  4. }
  5. ?>

fetch.php

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

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

logout.php

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

That ends this tutorial.

Happy Coding :)

Comments

Submitted bykanberon Thu, 05/17/2018 - 05:05

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.):
  1. 'use strict';
  2.  
  3. app.controller('datalist', ['$scope', 'listServices', function($scope, listServices){
  4.  
  5. var listeistek = listServices.listele();
  6. listeistek.then(function(response){
  7. $scope.listem = response.data ;
  8. });
  9.  
  10. }]);
Alternative codes for 'datalist.js' are (the result is obtained with this code):
  1. 'use strict';
  2.  
  3. app.controller('datalist', ['$scope', 'listServices', function($scope, listServices){
  4.  
  5. var listeistek = listServices.listele();
  6. listeistek.then(function(response){
  7. $scope.listem = response.data[0] ; //only one record fetch
  8. });
  9.  
  10. }]);
The 'listServices.js' code looks like this:
  1. 'use strict';
  2.  
  3. app.factory('listServices', function($http, $location, sessionService){
  4. return{
  5. listele: function(){
  6. var datalistem = $http.get('fetchListe.php');
  7. return datalistem;
  8. }
  9.  
  10. }
  11. });
The 'fetchListe.php' code looks like this:
  1. <?php
  2. session_start();
  3. $con = new mysqli("localhost", "root", "", "kabul");
  4. $sel = mysqli_query($con,"SELECT ID,AH_ID,DATE_FORMAT(TARIH,'%H:%i:%s') AS TARIH,HASTA_ID,AD,SOYAD,YAS,AHX FROM kabul");
  5. $data = array();
  6.  
  7. while ($row = mysqli_fetch_array($sel)) {
  8. $data[] = array("ID"=>$row['ID'],
  9. "AH_ID"=>$row['AH_ID'],
  10. "TARIH"=>$row['TARIH'],
  11. "HASTA_ID"=>$row['HASTA_ID'],
  12. "AD"=>$row['AD'],
  13. "SOYAD"=>$row['SOYAD'],
  14. "YAS"=>$row['YAS'],"AHX"=>$row['AHX']);
  15. }
  16. echo json_encode($data);
  17.  
  18. ?>
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:
  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. .when('/listele', {
  14. templateUrl: 'listele.html',
  15. controller: 'datalist'
  16. })
  17. .otherwise({
  18. redirectTo: '/'
  19. });
  20. });
  21.  
  22. app.run(function($rootScope, $location, loginService){
  23. //prevent going to homepage if not loggedin
  24. var routePermit = ['/home'];
  25. $rootScope.$on('$routeChangeStart', function(){
  26. if(routePermit.indexOf($location.path()) !=-1){
  27. var connected = loginService.islogged();
  28. connected.then(function(response){
  29. if(!response.data){
  30. $location.path('/');
  31. }
  32. });
  33.  
  34. }
  35. });
  36. //prevent going back to login page if sessino is set
  37. var sessionStarted = ['/'];
  38. $rootScope.$on('$routeChangeStart', function(){
  39. if(sessionStarted.indexOf($location.path()) !=-1){
  40. var cantgoback = loginService.islogged();
  41. cantgoback.then(function(response){
  42. if(response.data){
  43. $location.path('/home');
  44. }
  45. });
  46. }
  47. });
  48. });
The 'listele.html' code looks like this:
  1. <div class="row">
  2. <div class="col-md-4 col-md-offset-4">
  3. <h4>listele .html</h4>
  4. <p>ID: {{ listem.ID }}</p>
  5. <p>AD: {{ listem.AD }}</p>
  6. <p>SOYAD: {{ listem.SOYAD }}</p>
  7. <p>YAS: {{ listem.YAS }}</p>
  8. <p>TARİH: {{ listem.TARIH }}</p>
  9. <p>AİLE HEKİMİ: {{ listem.AHX }}</p>
  10.  
  11. <a href="" class="btn btn-danger" ng-click="logout()"><span class="glyphicon glyphicon-log-out"></span> Exit</a>
  12.  
  13. <tbody>
  14. <tr ng-repeat="c in listem">
  15. <td>{{c.ID}}</td>
  16. <td>{{c.AD}}</td>
  17. <td>{{c.SOYAD}}</td>
  18. <td>{{c.TARIH}}</td>\
  19. <td>{{c.YAS}}</td>
  20. </tr>
  21. </tbody>
  22. </div>
  23. </div>
  24. </div>
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?

Add new comment