session - Store, check and renew token bearer on PHP

one text

So I got this api that returns a token bearer with also the expiration which is actually 5 minutes (300 seconds).

So I've started storing it into a session variable after session start:

function check_token_status() {
if (empty($_SESSION['token_bearer'])) {
$echo = "new token added.";
$_SESSION['token_bearer']=get_new_token(); //function that retrieves the token.
} else {
$echo = "reusing token.";
}

So, that function is completely useless because the $_SESSION['token_bearer'] will be always empty on a new session. So I first need to fulfill the $_SESSION['token_bearer'] session value with the value returned by the get_new_token. The thing is that i've tried to extract the value from expires_in key which is 300 seconds (5 mins) and somehow count, if the current time is beyond the expires_in then renew the token.

function check_token_status() {
    if (empty($_SESSION['token_bearer'])) {
    $echo = "new token added."; //first time run
    $_SESSION['token_bearer']=get_new_token(); //function that retrieves the token.
    } else { //the token is still available to use.
    if (isset($_SESSION['start']) && (time() - $_SESSION['start'] > $_SESSION['expires_in'])) {
$_SESSION['token_bearer']=get_new_token();
echo "token time exceeded, requesting a new token.";
} else {
$_SESSION['token_bearer']=$_SESSION['token_bearer'];
}
    }
}

Since this is required for an external api and is not related with the current session login in, it should renew each time it exceeds the 5 min and if not reuse the current value of the token. But somehow is always trying to renew the token instead of using the current on which has until 5 minutes to reuse it.

Any tip will be appreciated.

Source