首页 文章

AngularJS和PHP在每个请求中创建新的Session

提问于
浏览
3

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

所以我在index.php文件中包含了许多php文件,其中初始化了$ app?我不确定它是否与它有任何关系,但它可能会理解后续代码的作用 .

的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应用程序发布对“ / employees / login”的调用时,会话变量已设置,并且会返回会话['userID'] . 但是,如果在此之后我调用' / employees / status'来查看用户是否已登录,则会话变量为空 . 在保存会话变量的tmp文件夹中,我可以看到为每个请求创建的新文件 .

我究竟做错了什么?任何帮助,将不胜感激 .

谢谢!

EDIT

我试过在这里简化一些事情来看看发生了什么 . 它必须与我的角度页面张贴和疾病表明我的意思 .

的index.php

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

如果我只是访问该页面并继续点击刷新,我的会话变量正在工作,并且它一直在上升 . 因此会话变量正在工作 .

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

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

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

谢谢!

1 回答

  • 1

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

    因此documentation:"By default, in cross-site XMLHttpRequest or Fetch invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object or the Request constructor when it is invoked."

    在角度中,它通过添加配置行来完成:

    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
    

相关问题