无法确定PHP中的会话何时处于活动状态

So I want to be able to tell, in PHP, whether a session is currently active. I thought that this would be easy by either using session_status() or session_id(), but both return inconclusive results.

My PHP looks like this

if (session_id() == "") {
    echo json_encode("nope");
} else {
    echo json_encode("yep");
}

if (session_status() === PHP_SESSION_DISABLED) {
    echo json_encode("disabled");
} elseif (session_status() === PHP_SESSION_NONE) {
    echo json_encode("none");
} else {
    echo json_encode("active");
}

$handler = new DatabaseSessionHandler();
session_set_save_handler($handler, true);
session_start();

And I have an Angular app making http calls to this script to basically activate its session.

I've been testing this, and when I visit the site for the first time, no session_id is found and the session_status() returns back "none", as they both should. But the problem is, when I refresh the page, and this PHP script is runs, but this time I have an active session (the PHP session cookie shows up in my browser), session_id is still acting like none exists. And also, session_status() returns back, mistakenly "none".

Any ideas would be greatly appreciated, thanks!

Edit 1: A few people have mentioned that putting the session_start() in front of testing if it is active or not should work. When I do this, a session_id is always found, and the session_status() always returns back "active". Even when a fresh new user visits the site, this still happens.

I am not sure if this will solve your problem, but you could check if your session directory is writable:

if (!is_writable(session_save_path())) {
    echo 'Session path "'.session_save_path().'" is not writable for PHP!'; 
}

A question related to that is at PHP Session not Saving.

Elsewhere try the following:

if (session_id() == "") {
    session_start();
    echo json_encode("nope");
} else {
    echo json_encode("yep");
}

The session won't be active until you call session_start(), which you don't do until after testing to see if the session is active.

You should call session_start() at Top of the page and then perform the condition on it. In your case you are not starting session and you are testing for it.