Home > database >  How can React read a session SET in PHP
How can React read a session SET in PHP

Time:11-10

The form is handed to a php script on the same domain and php creates a session and session values are declared.

I want react to read the session data created by the PHP script

CodePudding user response:

I suggest using cookies instead if security isn't an issue or else try something like this:

session.php

<?php session_start(); echo json_encode($_SESSION); ?>

code.js

fetch('session.php', {credentials: "same-origin"})
  .then(response => response.json())
  .then(data => console.log(data));

CodePudding user response:

Just embed the information you need from PHP in the HTML.

<script>
const sessionData = {
    "country": <?= json_encode($intlContext->getCountryCode()); ?>,
    "someSessionValue": <?= json_encode($_SESSION['someValue']); ?>
};
<script>

If you cannot read the data from script straight away in react, you can pick them from a meta field:

<meta name="country" content="<?= htmlentities($intlContext->getCountryCode()); ?>">
<meta name="someSessionValue" content="<?= htmlentities($_SESSION['someValue']); ?>">

There is no need to pass a PHP session ID to react. You cannot verify nor access the session backend from PHP within react.

  • Related