lundi 1 janvier 2018

Weird condition behaviour in PHP

Hello I've got following code:

$cleanToken = $token->cutToken($auth_header);

if($cleanToken)
{
    if($user->logout($cleanToken))
    {
        http_response_code(200);
    }
    else
    {
        http_response_code(401);
    }
    echo json_encode('true: ' . $cleanToken);
}
else
{
    echo json_encode('false' . $cleanToken);
    http_response_code(401);
}

cutToken function is returning string or false. Above code is giving me error in console

Failed to load http://localhost/obiezaca/v2/api/auth/doLogout.php: Response for preflight has invalid HTTP status code 401

I'm also not able to see any response.data although I'm consoling it out on front-end. When I delete http_response_code(401); from the last line in else error stops showing code seems to work and I'm able to see true: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjIwIn0.EAEOBEDxweNnMB-iHCD5qFcn_VYKguHO8Vr3jImChhc response in my console.

So to make it clear - when I have http_response_code(401); present in else of first condition code is not working and is giving me error. When I delete this line code seems to work, it is not giving me any error and I'm able to see true ..token.. in console.

It is very weird for me because it looks like adding http_response_code there is changing $cleanToken whether it is giving true or false what is impossible.. What is going on here?

cutToken function is:

public function cutToken($auth_header)
{
    if (isset($auth_header))
    {
        $dirtyToken_trimmed = trim($auth_header);
        if (!empty($dirtyToken_trimmed))
        {
            if(preg_match('/Bearer\s(\S+)/', $dirtyToken_trimmed, $matches))
            {
                return $matches[1];
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

Aucun commentaire:

Enregistrer un commentaire