Im developing an API in php, and i ran into a problem, basically http_response_code(int $code);
behaviour is unpredictable, it just always gets sent at all costs if present anywhere in the code, and after that, naturally i cannot set another http_response_code(int $otherCode)
as headers are already sent. I do not know what i am doing wrong, but i think i can boldly assume that http_response_code(int $code);
can be used conditionally because it makes all the sense for me.
My question is, how this problem should be solved? I have to use the correct response codes, is there a working alternative which does not use rng to decide if it obeys an if statement?
PHP version is 7.4.5
smol version:
/* CASE 1 */
if(false){
http_response_code(401);
echo json_encode($someErrorMessage);
die;
}
http_response_code(200);
echo json_encode($someResponse);
//Expectation: 200 response code & $someResponse json
//Result: 401 response with no message at all
/* CASE 2 */
if(false){
//http_response_code(401);
echo json_encode($someErrorMessage);
die;
}
http_response_code(200);
echo json_encode($someResponse);
//Expectation: 200 response code & $someResponse json
//Result: 200 response code & json
Actual code:
try{
if(empty(getallheaders()['Authorization'])){
throw new WSException("oAuth access token missing from request");
}
$user = new Admin(getallheaders()['Authorization']);//Authenticate user, get data(throws WSException)
}
catch(WSException $e){ //Unauthenticated, send 401 header + message
http_response_code(401);
echo $e->getMessage();
die;
}
/* GET USER DATA (SELF) */
#region GET USER DATA (SELF)
if($r == "get_self"){ //Return user object as json
try{
/* BASIC DATA //$user already has all user data after authentication with `new Admin();` */
if(!empty($user->profile_picture)){ //TODO: Function needed to filePHP
$user->profile_picture = "{path/to/file.php}".$user->profile_picture;
}
http_response_code(200);
echo json_encode($user, JSON_UNESCAPED_SLASHES); //Unescaped slashes to send correct urls
//An error cant really happen here rn, but when there is a possibility, it would be:
//if($someError){
// http_response_code(401);
// throw new WSException("Something gone wrong");
//}
}catch(WSException $e){
echo json_encode($e->getMessage());
}
die;
}
#endregion
question from:
https://stackoverflow.com/questions/65598315/php-http-response-codecode-gets-executed-in-a-totally-false-if-statement 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…