1

When I run the following code on my Azure Web App (php 7.4 or 8.0) :

<?php

try {
  throw new Exception('x');
}catch (Exception $e) {
  echo '1 '; // If i comment this line, http status code will be 400...
  http_response_code(400);
}

echo '3 '; 
echo http_response_code();

the result is "1 3 400", but when I check my http status code, I have 200 (same on several browser).

And when I comment the line echo '1 '; the http status code become 400.

From my point of view, I always expect 400 as http status code result with this code...

Clément Baconnier
  • 5,718
  • 5
  • 29
  • 55
Sybaris
  • 41
  • 5

2 Answers2

0

Setting the response code implies setting a response header. These headers can only be set, as long as there is no output sent to the client.

To check, if you can add more http headers, you can use the function headers_sent.

In your example:

    try {
        throw new Exception('x');
    } catch (Exception $e) {
        echo '1 '; // If i comment this line, http status code will be 400...

        if(headers_sent()) { //check if headers were sent already
            print 'oops, headers have been sent already, not possible to add some more :-(';
        }

        http_response_code(400);
    }
    echo '3 ';
    echo http_response_code();

On some servers, it is possible to echo a little amount of output, before the headers are finally sent. That happens, because an output cache of a certain size has been configured. (using the output_buffering setting) So, it is very likely that this setting is set to 0 on your server. Then the headers are already sent with the first byte of output, even it is not visible.

More information can be found in an older question about sending headers and making some output: https://stackoverflow.com/a/8028987

akrys
  • 563
  • 1
  • 3
  • 9
  • Thanks for the answer. It fit well... That explain also why I had a difference between my local php and Azure... – Sybaris Feb 01 '22 at 16:41
0

After reading Akrys' answer, I understand that the exception has nothing to do with it.

A better question would have been:

Why the following code returns an http status code 200 ?

 echo 'A'; 
 http_response_code(400);

And why the following code returns an http status code 400 ?

And as you answer "On some servers, it is possible to echo a little amount of output, before the headers are finally sent."

 http_response_code(400);
 echo 'A'; 

And that depends on output_buffering setting that explains why I have always an http status code 400 on my local php server...

Thanks for the answer...

Sybaris
  • 41
  • 5