3

I have a question of session PHP in React. I have to create an online shop in React and PHP. I currently programming a shopping cart. To do this, I have to use PHP Session. I can't use JWT, so my questions are:

  • How to start a Session if I can't include PHP code in index.html (react-create-app, MVC, I can't include start_session() at the beginning of the page)
  • How to retrieve data from Session (is it possible by ajax?) I have never used PHP and React. So far I have only used restful API.

Please help.

Aircod
  • 59
  • 1
  • 5
  • Suppose you're creating the react app with the cli tool, then there's no need to start the session in any of the static assets. Simply start it in the php code handling your api requests (possibly a front controller, for simplicity). – Yoshi Apr 30 '20 at 07:00

2 Answers2

1

Yes i think you can. Check this question and the most voted answer:

The answer is yes: Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way. From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.

Do AJAX requests retain PHP Session info?

-4

What you can do is initialize a Javascript variable with your PHP variable. This is possible because PHP, a server-side language executes on the page before Javascript, so it's almost like entering plain text where the right-hand side of the JS line is.

An example would be something like this in your index.html file:

index.php (you must rename your index.html file to index.php so the computer knows there's some PHP in there). Also, must ensure PHP is installed in your local environment hosting this. Something like npm install PHP, brew install PHP, or yum install PHP will do.

<script>
// Note here: we must ensure name is set,
// otherwise it would look something like 
// let name = ;
// this would cause an error
// that is why I check the value is present with isset()
let name = <? echo isset($name) ? $name : "Air"; ?>;

</script>

Therefore, I think you would just need to ensure your environment supports PHP. You can also use a subroutine/webservice/ajax call to do the same; however, this is a little bit more complex in regards to its setup.

fungusanthrax
  • 192
  • 2
  • 13