Muh Fadly Sangadji Muh Fadly Sangadji - 4 years ago 125
PHP Question

How to get session from PHP into AngularJS for redirect

I try to made a login system but I want the session can be taken from PHP code. If session login is

false
or
null
it will redirect to login page.
Here my run AngularJS code :

app.run(["$rootScope", 'adminService', '$location', function($rootScope, adminService, $location) {
$rootScope.$on("$routeChangeStart", function() {
$location.path('/login');
});
}]);


Routing code :

app.config(function($routeProvider){
$routeProvider.when('/', {
templateUrl: 'welcome.html'
}).when('/administrator', {
templateUrl: './part/administrator.html',
controller: 'adminPageControl'
}).when('/administrator/:id_admin', {
templateUrl: './part/addit-administrator.html',
}).when('/alternatif', {
templateUrl: './part/alternatif.html',
controller: 'alternatifPageControl'
}).when('/alternatif/:id_alternatif', {
templateUrl: './part/addit-alternatif.html'
}).when('/skala', {
templateUrl: './part/skala.html',
controller: 'skalaPageControl'
}).when('/skala/:id_skala', {
templateUrl: './part/addit-skala.html'
}).when('/kriteria', {
templateUrl: './part/kriteria.html',
controller: 'kriteriaPageControl'
}).when('/kriteria/:id_kriteria', {
templateUrl: './part/addit-kriteria.html'
}).when('/klasifikasi', {
templateUrl: './part/klasifikasi.html',
controller: 'klasifikasiPageControl'
}).when('/klasifikasi/:id_klasifikasi', {
templateUrl: './part/addit-klasifikasi.html'
}).when('/analisis', {
templateUrl: './part/topsis.php',
controller: 'analisisPageControl'
}).when('/login', {
templateUrl: './login.html'
}).when('/logout', {
template: 'logout'
}).otherwise({
redirectTo: '/'
});
});


PHP function session code :

function logincheck(){
return $_SESSION['authid'];
}

logincheck();

Answer Source

The other answer is right. It's a good practice to communicate with backend by using an API, because AngularJS is made for SPA. However if you insist on using session, it's ok. You can create a router such as /api/logincheck

PHP:

public function index()
{
    $res = ['login'=>false];
    if(isset($_SESSION['authid']))
    {
        $res['login'] = true;
    }
    echo json_encode($res);
}

JS:

$http.get('http://XX/api/checklogin').success(function(res){
    if(res.login)
    {
        #handle it
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download