John Davidson

php - $_SESSION is always null

0 comments
Message:


I have 2 runtime environment simultanously :



  • Front-end : Angular JS (localhost:4401) run with VS Code (ng serve)

  • API : PHP run with WAMP (localhost) attached to a database.


For each call from my front-end to my API, I call session start like this :


(from "session.php" which is included in each *.php page)


session_start();

// Make sure we have a canary set
if (!isset($_SESSION['canary'])) {
session_regenerate_id(true);
$_SESSION['canary'] = [
'birth' => time(),
'IP' => $_SERVER['REMOTE_ADDR']
];
}

I noticed that my $_SESSION variable has always a "null" value while executing code and it can't retrieve the session initially created (directory: wamp64\tmp).


Example of my call from Angular :


  checkLoginStatus(){
// Used to check if stay logged in cookie is set - autologin...
return this._http.get<loginResponse>(environment.api+"api/check_autologin.php").pipe(catchError(this.handleError))
}

Do you have any idea ?
Thanks in advance.



My Answer:
Angular JS front-end code)

javascript
$http({
method: 'POST',
url: 'http://localhost/api.php',
data: {
// data to send to API
},
withCredentials: true
}).then(function(response) {
// handle response from API
});


And in my PHP API code, I have the following:

php
session_start();
$_SESSION['test'] = 'test';
echo json_encode($_SESSION);


However, when I make a call from my front-end to my API, the `$_SESSION` variable is always null.

This is because the `$_SESSION` variable in PHP is specific to each session, and since you are making separate calls from your front-end to your API, each call is considered a separate session.

To maintain session state across multiple calls, you can use cookies or tokens to store session information and pass it back and forth between your front-end and API.

Alternatively, you can look into using a session management solution like JWT (JSON Web Tokens) to handle authentication and session management in a stateless manner.

Overall, the issue you are facing is due to the nature of PHP sessions and how they are handled in a stateless environment like a REST API.

Rate this post

3 of 5 based on 2155 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us