我正在尝试使用 Silex 创建 REST API。它工作得很好,但现在我想使用 session 变量来跟踪用户。我尝试使用常规的 php session 变量和 SessionServiceProvider。在我的生活中, session 变量不会持续存在于页面请求中。查看我的临时 session 文件夹,似乎每个请求都会创建一个新 session 。
所以我在 $app 初始化的 index.php 文件中包含了很多 php 文件?我不确定这是否与它有任何关系,但它可能使后续代码的作用变得有意义。
索引.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();
员工.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”的调用时,会设置 session 变量并返回 session ['userID']。但是,如果在那之后我立即调用“{url}/employees/status”来查看用户是否已登录,则 session 变量为空。在保存 session 变量的 tmp 文件夹中,我可以看到为每个请求创建的新文件。
我做错了什么?任何帮助将不胜感激。
谢谢!
编辑
我已经尝试简化这里的事情以查看发生了什么。它必须与我的有 Angular 的页面发布一起显示我的意思。
索引.php
$app->get('/hello', function () use ($app){
session_start();
$num = $_SESSION['idea'] ? $_SESSION['idea'] : 1;
$_SESSION['idea'] = $num+1;
echoResponse(200, $_SESSION['idea']);
});
如果我只是访问该页面并不断点击刷新,我的 session 变量就会起作用并且它会不断增加 1。因此 session 变量正在工作。
然而,当我尝试从我的 Angular 应用程序调用此页面时:
$scope.hello = function(){
$http.get('https://viromo.com/cubex/api/hello').then(function(results){
console.log(results);
})
};
结果不断发回相同的数字,但没有增加。不知道为什么会这样。我更新了标题和标签以更好地反射(reflect)我的问题目标。
谢谢!
最佳答案
在我的例子中,这是因为在请求 header 中设置 cookie 的 Angular 缺少配置。
据此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
关于php - AngularJS 和 PHP 在每次请求时创建新的 Session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094618/