darxysaq
darxysaq

Reputation: 761

PHP - Sessions and REST

I need help with understanding what I am doing wrong. I am building RESTful API for inner use. I have 2 endpoints - /login and /logout. On login I am validating user input and creating a session - Works good. On logout I would like to destroy the session but it says "session_destroy(): Trying to destroy uninitialized session in..."

Here is the code:

Login:

$api->post('/login', function () {
if(some validations)
{
    session_name('lalala');
    session_start();
    session_regenerate_id(true);
    setcookie(session_name(), session_id(), 0, '/', 'xxx.xxx.xxx.xxx', false, true);
}
});

Logout:

$api->post('/logout', function () {
session_unset();
session_destroy(); // here it fails

setcookie('lalala', "", 1);
setcookie('lalala', false);
unset($_COOKIE);

});

Please note, I am using an IP address instead of a domain name. I don't believe there is a difference but for your attention.

Can you please help me understand what is wrong here?

Upvotes: 0

Views: 1176

Answers (1)

Marek
Marek

Reputation: 7423

You have to call:

session_name('lalala');
session_start();

before session_unset()

Instead of setcookie(...) use session_set_cookie_params() before session_start()

Upvotes: 2

Related Questions