嗨,我目前正在尝试使用Angular 6和PHP的Web API建立登录。我正在尝试使用具有特定角色的特定帐户登录时显示此消息。但是,只有post.php中显示了帖子消息,但是说我已登录的消息出现在auth.php中。我应该如何解决这个问题?
auth.php:
<?php
session_start();
require 'connection.php';
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST) && !empty($_POST)){
$username = $_POST['username'];
$password = $_POST['password'];
$hashed = md5($password);
$stmt=$con->prepare("SELECT * FROM user WHERE username= :u AND password=:p");
$stmt->execute(array(':u' => $username, ':p' => $hashed));
// $row = $stmt->fetchColumn();
$row = $stmt->fetchColumn();
//user is logged in
if ($row >= 1 ) {
$row2 = $stmt->fetch(PDO::FETCH_ASSOC);
if($row2['role']== 0){
// buat session login dan username
$_SESSION['username'] = $username;
$_SESSION['role'] = "Admin";
}else{
$_SESSION['username'] = $username;
$_SESSION['role'] = "Tenant";
}
?>
{
"success": true,
"secret": "You are logged in"
}
<?php
}else{
?>
{
"success": false,
"message": "Invalid Credentials"
}
<?php
}
}else{
?>
{
"success": false,
"message": "Only POSt access accepted"
}
<?php
}
?>
session.php:
<?php
session_start();
require 'connection.php';
if(isset($_SESSION['role'])){
$role = $_SESSION['role'];
if($role == "Admin"){
?>
{
"message": "You are logged in as an adminstrator",
"success": true
}
<?php
}elseif($role == "Tenant"){
?>
{
"message": "You are logged in as a tenant",
"success": true
}
<?php
}else{
?>
{
"message": "You are not authorized",
"success": true
}
<?php
}
}else{
?>
{
"message": "Only post",
"success": true
}
<?php
}
?>
user.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface myData{
message: string,
success: boolean
}
@Injectable({
providedIn: 'root'
})
export class UserService {
public url = 'http://localhost/api/';
constructor(private http: HttpClient) { }
getSomeData(){
return this.http.get<myData>(this.url + 'session.php')
}
}
admin.component.ts:
import { Component, OnInit } from '@angular/core';
import { UserService } from '../user.service';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
message = "Loading..."
constructor(private user: UserService) { }
ngOnInit() {
this.user.getSomeData().subscribe(data => {
this.message = data.message
})
}
}