Table of Contents
Tutorial: Login with Session using AngularJS in PHP/MySQLi with Source Code
Getting Started on Login with Session using AngularJS in PHP/MySQLi
How to use Login with using AngularJS in PHP/MySQL is our tutorial for today. I’ve used CDN for Bootstrap, AngularJS and Angular Route, so you need an internet connection for them to work.
Creating our Database on Login with Session using AngularJS in PHP/MySQLi
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 image below for detailed instruction.
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;
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.
</html4stri<!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> <h2>login.html</h2> This contains our login form. <html4strict> <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
This is a homepage after a successful login.
<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
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'); } }); } }); });
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; } } });
session.php
This is our PHP code in checking if session has been set.
<?php session_start(); if(isset($_SESSION['user'])){ echo 'authentified'; } ?>
fetch.php
This is our PHP code in fetching the details of the logged in user.
<?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 is out PHP code in destroying our current PHP Session.
<?php session_start(); session_destroy(); session_commit(); ?>