Skip to content
Advertisement

Starting a php session from react with an axios call does not keep the session alive, but doing it with postman works just fine

I am aware other questions like this one exist, i have failed to implement any of those successfully, meaning none have worked, whether due to a fault of my own or their inherent impotency to solving this problem.

The environment :

I am serving the php project with php -S 127.0.0.1:8080 and have a react front end started on the default port (3000) with npm start. I am using axios for making the request to the server.

The relevant code :

I have 2 files that really matter :

  • LoginPage.js is where my react code is, I am making 2 requests, the first one is to mimic authentication and start the session and the second request is to check if the session is still alive:
JavaScript
  • test1page.php is where my php code is :
JavaScript

The problem :

My problem is that, while the first request authenticates no problem :

JavaScript

The second request does not find a live session :

JavaScript

Tried Solutions/Debugging :

I have tried many solution, including setting withCredentials: false and true. Setting it to true causes a Cors error. I have added and removed all kinds of headers from the php file (some for Cors, and some to try to solve this problem) :

JavaScript

I have tried postman and sending a request to start the session, then another to check if it is alive works just fine :

  • First request :

you are logged in{
"username": "username"
}

  • Second request :

enter image description here

Advertisement

Answer

I found the solution. A detailed explanation can be found in this article about Cors. The relevant part is in the Credentials and Cors section. The short answer is that you have to set the withcredentials flag to true, which will cause a Cors error issue, which you can then fix by adding the appropriate headers in the backend :

JavaScript

So this is how my pages look now that everything is working fine :

  • LoginPage.js :
JavaScript
  • test1page.php :

    JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement