PHP Session 在 Angular 6 项目中不起作用 [英] PHP Session doesn't work in Angular 6 project

查看:28
本文介绍了PHP Session 在 Angular 6 项目中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using angular 6 for frontend and PHP for backend (WAMP) and I want to make a login system. When someone enters valid credentials I want him to get redirected to http://localhost:4200/home

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

I have auth.php which sets the session variables when someone enters valid username/password and verify.php to check if the session variables are set. Although the app redirects me to home, verify.php can not see the session variables.

那些是我的文件:

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 中获取用户名和密码并将其发送到服务

which takes the username and password from html and sends it to the service

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 未定义.

My home.component.ts has this class and I want to display in html "You have the right" but it displays "You DONT have the right" because the variable loggedin is undefined.

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() is implemented in user.service.ts

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

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

Is there a way to fix this problem with session or do I have to use another method of checking in angular?

谢谢.

推荐答案

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

You can't set SESSION on one domain and use on other domain, From your code it's clear you are using two different port, if you want to use sessions javascript and PHP must be on the same Domain/ports.

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

If you want to use different domains/ports then you have to find other ways like token based auth, i.e in auth.php after successful login create a token which will be saved in your database, send back that token in your successful response.

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

in your angular save that token to storage ( or wherever you prefer ) and retrieve use data from your PHP API using that token.

因此,当您在 user.service.ts 中进行调用时,您的 URL 应包含令牌

so when you do a call in user.service.ts your URL should contain the token

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 存储和数据库中删除令牌.

p.s when logout make sure to either expire or delete token from angulare storage and database.

这篇关于PHP Session 在 Angular 6 项目中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆