I'm building a website, I have 2 pages, one for login and one to upload a file.
When the user logs, i set the ID of that user fetched from a Database into the $_SESSION
variable, when the user goes to the second page, he can upload a file, and a reference to that file and the ID are stored into the database.
My front-end btw sits on a completely different domain, so when the user will upload the file, the $_SESSION
variable will be empty, how can I solve?
PHP check login page on 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
}
$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);
?>
Front end for the login written in ReactJS on example2.com
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();
};
At this point the $_SESSION
is set.
uploadFile.php on example.com
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;
}
}
);
};
Even in localhost, this doesn't work