【发布时间】:2020-02-27 16:38:09
【问题描述】:
我正在建一个网站,我有 2 个页面,一个用于登录,一个用于上传文件。
当用户登录时,我将从数据库中获取的用户 ID 设置为 $_SESSION 变量,当用户转到第二页时,他可以上传文件,以及对该文件的引用和 ID存储到数据库中。
我的前端btw位于一个完全不同的域,所以当用户上传文件时,$_SESSION变量将为空,我该如何解决?
example.com 上的 PHP 检查登录页面
<?php
session_start();
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
$a = headers_list();
require "Connessione.php";
$connessione = new Connessione();
$ris = $connessione->getUtente($_POST['id']);
if($risposta['esisteGia'])
{
$_SESSION['ID'] = $ris[0]['IDUtente'];
$_SESSION['Tipo'] = $ris[0]['Ruolo'];
}
echo json_encode($risposta);
?>
example2.com 上用 ReactJS 编写的登录前端
const esisteGia = () => {
async function controllaCheEsistaGia() {
let udid = "123";
let data = new FormData();
data.append("id", udid);
let risposta = await fetch(
"https://example.com/checkLogin.php",
{
method: "POST",
body: data,
credentials: "include"
}
);
risposta = await risposta.json();
console.log(risposta);
}
controllaCheEsistaGia();
};
此时$_SESSION 已设置。
在 example.com 上上传文件.php
session_start();
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
if(!isset($_SESSION['ID'])). //Here the session is now empty again
{
header("Location: {$_SERVER['HTTP_ORIGIN']}/Login");
die();
}
header('Content-Type: application/json; charset=utf-8');
$filePDF = $_FILES['pdfDaCaricare']['tmp_name']; //Also the $_FILES is not set, and I don't know why
example2.com/uploadFile
const caricaFile = async e => {
const fd = new FormData();
fd.append("pdfDaCaricare", file);
await axios.post(
"example.com/uploadFile.php"
fd,
{
method: "POST",
credentials: "include",
headers: {
"content-type": "multipart/form-data"
},
onUploadProgress: function(progressEvent) {
let percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
document.getElementById("percentuale").innerText = percentCompleted;
}
}
);
};
即使在本地主机中,这也不起作用
【问题讨论】:
-
我的前端 btw 位于一个完全不同的域这是什么意思。你的意思是你登录一个域并从另一个域上传???#
-
永远不要在会话中使用密钥
['ID'] -
RiggsFolly:我的后端 php 文件在一个域中,而 HTML、CSS 和 JS 文件在另一个域中。 Zeljka:这可能是问题吗?
-
@DavideVitiello 将其更改为
['myId']或其他任何内容,您会看到 :) -
@DavideVitiello 抱歉,我刚刚在 php 7.3 上对其进行了测试,它与
['ID']一起使用,所以这可能不是问题。但总的来说,它总是建议在会话中定义您自己的自定义键。并始终检查isset && !empty