Sending dynamic status headers from PHP

Sending the right HTTP protocol for headers from PHP is easy, you just need to find which HTTP protocol your server is using. Most servers will be using HTTP/1.1, but allowing PHP to serve the protocol version for you means safer headers for older systems and greater cross-platform compatibility.

Rather than sending

header( 'HTTP/1.1 404 Not Found' );

we're going to send

header( $_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found' );

where

$_SERVER['SERVER_PROTOCOL']

gives us the HTTP protocol which matches the previous 'HTTP/x.x' format.

This can be used with any header that requires the HTTP protocol to be sent, it is not limited to 404 errors in particular.

EDIT 2015-10-10:

Available from PHP 5.4.0, function 'http_response_code' is the alternative to this and sends the correct protocol along with the correct status code description.

Usage: http_response_code(404);
Output: HTTP/1.1 404 Not Found