【问题标题】:AngularJS and PHP creates new Session every requestAngularJS 和 PHP 为每个请求创建新的 Session
【发布时间】:2016-12-05 23:34:32
【问题描述】:

我正在尝试使用 Silex 创建一个 REST API。它工作得很好,但现在我想使用会话变量来跟踪用户。我尝试使用常规的 php 会话变量和 SessionServiceProvider。在我的一生中,会话变量不会持续存在于页面请求中。查看我的临时会话文件夹,似乎每个请求都在创建一个新会话。

所以我在 $app 初始化的 index.php 文件中包含了许多 php 文件?我不确定这是否与它有关,但它可能对以下代码的作用有意义。

index.php

<?php

require_once 'vendor/autoload.php';

$config['displayErrorDetails'] = true;

$app = new Silex\Application();
$app->register(new Silex\Provider\SessionServiceProvider, array('session.storage.save_path' => dirname(__DIR__) . '/tmp'));

$app->before(function() use ($app){
    $app['session']->start();
});

require "../apiSource/classes/employees.php";
$app->run();

employees.php

<?php
use Symfony\Component\HttpFoundation\JsonResponse as JsonResponse;
use Symfony\Component\HttpFoundation\Request as Request;

class Employees
{
    private $database;

    function __construct()
    {
        $this->database = getDB();
    }

    function loginEmployee($loginInfo, $app){

        //.... check loginInfo with database of employee ....///
        if ($isEmployee) {

            $app['session']->set('userID', $employee['e_ID']);
            return array('success' => 'success', 'e_ID' => $employee['e_ID'], 'session' => $app['session']->get('userID'));
            //SUCCESS
        } else {

            return array('message' => 'Error.');

        }

    }

    function isLoggedIn($app){
        $stmt = $this->database->prepare("SELECT e_ID, e_Email FROM Employee WHERE e_ID = ?");
        $stmt->execute(array($app['session']->get('userID')));
        $employee = $stmt->fetch(PDO::FETCH_ASSOC);

        if(empty($employee)){
            return array('Error' => $employee, 'Session' => $app['session']->get('userID'));
        }

        return $employee;
    }

    function logout($app){

        $app['session']->remove('userID');
        return array('success' => 'success');

    }
}


$app->get('/employees/logout', function() use ($app) {
    $employees = new Employees();
    $results = $employees->logout($app);

    return new JsonResponse($results);
});

$app->get('/employees/status', function() use ($app) {

    $employees = new Employees();
    $results = $employees->isLoggedIn($app);

    return new JsonResponse($results);

});

$app->post('/employees/login', function(Request $request) use ($app)  {

    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());

    $employee = new Employees();
    $results = $employee->loginEmployee($data, $app);

    return new JsonResponse($results);
});

当我的 Angular 应用发布对“{url}/employees/login”的调用时,会话变量已设置,它确实返回了会话 ['userID']。但是,如果在那之后我立即调用“{url}/employees/status”来查看用户是否已登录,则会话变量为空。在保存会话变量的 tmp 文件夹中,我可以看到为每个请求创建的新文件。

我做错了什么?任何帮助将不胜感激。

谢谢!

编辑

我尝试在这里简化一些事情,看看发生了什么。它必须与我的角度页面发布有关,并且无法表达我的意思。

index.php

$app->get('/hello', function () use ($app){
    session_start();
    $num = $_SESSION['idea'] ? $_SESSION['idea'] : 1;
    $_SESSION['idea'] =  $num+1;
    echoResponse(200, $_SESSION['idea']);
});

如果我只是访问该页面并不断刷新,我的会话变量正在工作,并且它会不断上升。因此会话变量正在工作。

但是,当我尝试从我的 Angular 应用程序调用此页面时:

$scope.hello = function(){
  $http.get('https://viromo.com/cubex/api/hello').then(function(results){
    console.log(results);
  })
};

结果不断发回相同的数字而没有增加。不知道为什么会这样。我更新了标题和标签以更好地反映我的问题目标。

谢谢!

【问题讨论】:

  • 可能是cookies被禁用了..
  • 您是否使用 dev.js 检查了 PHPSESSID。浏览器上的工具?页面之间的值是否变化?
  • 您是否尝试过从中间件中删除 $app['session']->start() ?根据这个silex.sensiolabs.org/doc/providers/session.html似乎没有必要。
  • 不幸的是启用了 cookie,PHPSESSID 每次都得到一个新的 var,删除会话开始没有帮助

标签: php angularjs session silex


【解决方案1】:

在我的情况下,这是因为在请求标头中设置 cookie 的角度缺少配置。

据此documentation: “默认情况下,在跨站点 XMLHttpRequest 或 Fetch 调用中,浏览器不会发送凭据。调用时必须在 XMLHttpRequest 对象或 Request 构造函数上设置特定标志。”

在 Angular 中,它是通过添加配置行来完成的:

angular.module('app', ['your_dependencies...'])
.config(function ($httpProvider) {
    // Enabling the use of cookies in angular
    $httpProvider.defaults.withCredentials = true;
});

如果您使用 Apache 来托管您的后端,您可能需要编辑您的“.htaccess”,通过添加以下行来允许使用凭据:

# When using credentials flag, the wildcard '*' does not work, so you need to specify the site URL
Header always set Access-Control-Allow-Origin http://<your_site_url>
# Allowing credentials
Header always set Access-Control-Allow-Credentials true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    相关资源
    最近更新 更多