PHP $ _SESSION总是丢失值,这是怎么回事?

时间:2018-08-11 14:28:41

标签: php session

我将Angular 6用于前端,并将以下PHP代码(代码段)用作后端:

session_start();

switch ($_SERVER["REQUEST_METHOD"]) {
  case "GET":
    ...
    break;
  case "POST":
    if (isMatch("/user/login")) {
      if () {
        // if un & pw is ok
        ... // get the permission from db..., then
        $_SESSION['sid'] = session_id();
        $_SESSION['userName'] = $userName;
        $_SESSION['permissions'] = $permissions;
        sendResponse($response);
      } else {
        // if not
        sendResponse($response);
      }
    }
    if (isMatch("/file/upload")) {
      if (isset($_SESSION['sid'])) {
        // upload...
        sendResponse($response);
      } else {
        // no permission
        sendResponse($response);
      }
    }
    ...
    break;
}

前端的端点:

  postLogIn(user: LoggingInUser): Observable<any> {
    return this.http.post(`${environment.baseServerHref}/${ENDPOINTS.LOG_IN}`, user);
  }

  postFiles(formData: FormData): Observable<any> {
    return this.http.request(
      new HttpRequest('POST', `${environment.baseServerHref}/${ENDPOINTS.UPLOAD_FILE}`, formData, {reportProgress: true})
    );
  }

不幸的是,$ _ SESSION丢失了这些值,因此当我在身份验证(成功)后尝试通过另一个请求上传文件时,$ _ SESSION为空。

如何达到我想要的?

更新:

这是一个非常简单的例子:

session_start();
header("Access-Control-Allow-Origin: {$_SERVER["HTTP_ORIGIN"]}");

if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
  $_SESSION['count']++;
}

echo json_encode(array('sid' => session_id(), 'count' => $_SESSION['count']));

响应(我发送了3次请求):

{"sid":"nttlcglqhpufuuu1a8vvv43uo9","count":0}
{"sid":"i4lip1deia00f9hb51u20dv7rn","count":0}
{"sid":"p5gdh7315a9gvgsbsm2kt4lvts","count":0}

1 个答案:

答案 0 :(得分:0)

解决方案

我检查了这些人是否在我的问题下写了评论。

解决方案是...

-在PHP方面:

header('Access-Control-Allow-Credentials: true');

-在角度一侧:

return this.http.post(URL, user, {withCredentials: true});

withCredentials选项应设置为true。

谢谢大家:)