PHP Snippet - Close Connection With A Non-Standard HTTP-Status

Posted at

Send header Connection: close using <?php header('Connection: close');?> is simple enough.
When using a non-standard HTTP-status, make sure to put its definition (through header) first.

Here is the correct way of doing it:

<?php
header('HTTP/1.1 418 I\\'m a teapot', true);
header("Connection: close");
?>


You'll want to specify the HTTP-status, in-full,
in the example above I'm using the 418 I'm a teapot,
RFC2324 - Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) which, is a joke HTTP-status.

And although it is very much a real HTTP-status, you can not normally just put it at the end of header('Connection: closed', true, 418), since it will apparently won't be parsed correctly and simply return an error 500..

So to make sure it is 100% supported, always send the HTTP-status using header, unambiguously.

Some older Apache server will probably try to gzip-compress your response,
this can be also quickly avoided by flushing the output-buffer and specifying a zero-length content:

<?php
while(ob_get_level()>0){@ob_end_flush();}
header('HTTP/1.1 418 I\\'m a teapot', true);
header("Content-Encoding: none");
header("Content-Length: 0");
header("Connection: close");
?>


Actually when I'm thinking about it,
maybe you better even use HTTP 1.0 in the response,
since keep-alive is pretty much a given fact in HTTP 1.1 (unless declared otherwise).

So this might be a better way utilising it:

<?php
while(ob_get_level()>0){@ob_end_flush();}
header('HTTP/1.0 418 I\\'m a teapot', true);
header("Content-Encoding: none");
header("Content-Length: 0");
header("Connection: close");
?>


Ps.
If you wish to set the HTTP version dynamically, without messing with it, just replace the correct line in the code above with this one:
header(filter_input(INPUT_SERVER, "SERVER_PROTOCOL", FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) . ' 418 I\\'m a teapot');.