【问题标题】:PHP Session doesn't work in Angular 6 projectPHP 会话在 Angular 6 项目中不起作用
【发布时间】:2019-03-28 17:21:30
【问题描述】:

我在前端使用 Angular 6,在后端使用 PHP (WAMP),我想创建一个登录系统。当有人输入有效凭据时,我希望他被重定向到 http://localhost:4200/home

我有 auth.php 当有人输入有效的用户名/密码和 verify.php 来检查会话变量是否设置时设置会话变量。 虽然应用程序将我重定向到主页,但 verify.php 看不到会话变量。

这些是我的文件:

login-form.component.ts

loginUser(event) {
const target = event.target;
const username = target.querySelector('#username').value;
const password = target.querySelector('#password').value;

this.Auth.login(username, password).subscribe(data => {
  if(data.success) {
    this.router.navigate(['/home']);
  }
  else {
    window.alert(data.message);
  }
});
}

从 html 中获取用户名和密码并将其发送到服务

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'

interface myData {
  success: boolean,
  message: string
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  constructor(private http: HttpClient) { }

  login(username, password) {
     return this.http.post<myData>('http://localhost/angular6-app/api/auth.php', {username, password}, 
    {
      headers : {
          'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
      } 
    })

  }

auth.php

include 'config.php'; 
header('Access-Control-Allow-Origin: http://localhost:4200'); 

$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata)) {

    $request = json_decode($postdata);
    $username = $request->username;
    $password = $request->password;
    $sql = "select * from user where username = '$username'";
    $result = $conn->query($sql);              
    $row = $result->fetch_assoc();

    if($row['username'] == $username && password_verify($password, $row['password'])) //kanei verify me to hash pou exei ginei
        {
            $_SESSION['username'] = $username;  
            $_SESSION['loggedin'] = true;
            ?>
            {
                "success": true,
                "message": "You have logged in"
            }
            <?php
        }
    else {
        ?>
        {
            "success": false,
            "message": "Invalid credentials"
        }
        <?php
        }
}

?>

最后是 verify.php

<?php
session_start();
header('Access-Control-Allow-Origin: http://localhost:4200');

if (isset($_SESSION['loggedin'])) {
    ?>
    {
        "success": true,
        "message": "You have the right."

    } 
    <?php
}
else {
    ?>
    {
        "success": false,
        "message": "You DONT have the right."
    }
    <?php
}

?>

我的 home.component.ts 有这个类,我想在 html 中显示“你有权利”,但它显示“你没有权利”,因为变量 loggedin 未定义。

export class HomeComponent implements OnInit {

  message = "Loading..."

  constructor(private user: UserService) { }

  ngOnInit() {
    this.user.getSomeData().subscribe(data => {
      this.message = data.message;
    })
  }

getSomeData() 在 user.service.ts

中实现
getSomeData() {
    return this.http.get<myData>('http://localhost/angular6-app/api/verify.php');
  }

有没有办法解决这个问题,还是我必须使用另一种方法来检查 angular?

谢谢。

【问题讨论】:

    标签: php angular session localhost angular6


    【解决方案1】:

    一旦您构建 ngApp 并使其生效并将您的应用程序和 API 保存在同一目录中,您将获得会话值,您可以使用与上述相同的方法。因为您将使用相同的端口/域访问 API。

    【讨论】:

      【解决方案2】:

      您不能在一个域上设置 SESSION 并在另一个域上使用,从您的代码中可以清楚地看出您使用的是两个不同的端口,如果您想使用会话 javascript 和 PHP 必须在同一个域/端口上。

      如果您想使用不同的域/端口,那么您必须找到其他方式,例如基于令牌的身份验证,即成功登录后在 auth.php 中创建一个令牌,该令牌将保存在您的数据库中,在您成功的情况下发回该令牌回复。

      在您的角度将该令牌保存到存储(或您喜欢的任何地方)并使用该令牌从您的 PHP API 检索使用数据。

      所以当你在 user.service.ts 中调用时,你的 URL 应该包含令牌

      YOUR_TOKEN = '1234'//received after successfull login and saved in local storage
      return this.http.get<myData>('http://localhost/angular6-app/api/verify.php?token='+YOUR_TOKEN);
      

      在您的 verify.php

      $token = $_GET['token'];
      // check if token is valid in your database and send response
      

      p.s 注销时确保从 angulare 存储和数据库中过期或删除令牌。

      【讨论】:

      • 感谢您的建议! “将令牌保存到存储”是指本地存储或会话存储之类的东西?
      • 您可以在 angulare 中使用本地或 sessionStorage,这取决于您的需要,您也可以存储用户的完整会话而不是创建令牌,这只是为了给您一个想法。现在一切都取决于您如何使用用户数据
      猜你喜欢
      • 2019-05-29
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 2014-06-28
      • 2017-02-01
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多