Login with angularjs and php

I'm going to try and create a login system with angular and php. However, I don't know how Im going to handle sessions and redirects when the user is successfully logged in?

Should I start a session in the backend with PHP and then revert back to angular? Should I use window.location.href when I'm about to redirect the user?

+3


source to share


1 answer


You can use a php session and return it to an Angular service. Then you can share your information with the service to other controllers.

I recommend that you use ngRoute and a generic service containing user information. This method is very fast and safe.

I just edited my answer and gave you a quick example.



var doc = angular.module('doc',
[
    'ngRoute'
]);

doc.service('link', function () {//Creating my service
    this.user = false;//Here is my user object. I am changing these datas in the login section.

});

doc.config(function($routeProvider, $locationProvider) {
    $routeProvider
     .when('/homepage', {
         templateUrl: 'view/homepage.html',
         controller: 'homePage',
     })
    .when('/login', {
        templateUrl: 'view/login.html',
        controller: 'login',
    })
    $locationProvider.html5Mode(true);
});

doc.controller("login", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data.
    $scope.username = "";
    $scope.password = "";
    $scope.login = function () {
        $.get("/login.php", {username:$scope.username,password:$scope.password},function(data){
            if(data){
                link.user = JSON.parse(data); // I am parsing my json data and save to link.user
                $location.path("/homapage");
            }
        });
    }
});


doc.controller("homePage", function ($scope, $timeout, link, $location) { //As you see I sent 'link' as a parameter. So I can easily use my service and the user data.
    if(link.user){
        console.log(link.user); // I can access my user!
    }else{
        $location.path("/login");
    }
});

      

As you can see, my service contains my user data, which I initialized on the login page. Now I use them in my controllers easily.

+1


source







All Articles