http_response_code

Beschreibung

Parameter-Liste

response_code

The optional response_code will set the response code.

Rückgabewerte

If response_code is provided, then the previous
status code will be returned. If response_code is not
provided, then the current status code will be returned. Both of these
values will default to a 200 status code if used in a web
server environment.

FALSE will be returned if response_code is not
provided and it is not invoked in a web server environment (such as from a
CLI application). TRUE will be returned if
response_code is provided and it is not invoked in a
web server environment (but only when no previous response status has been
set).

Beispiele

Beispiel #1 Using http_response_code() in a web server environment

<?php

// Get the current response code and set a new onevar_dump(http_response_code(404));

// Get the new response codevar_dump(http_response_code());?>

Das oben gezeigte Beispiel erzeugt folgende
Ausgabe:

int(200)
int(404)

Beispiel #2 Using http_response_code() in a CLI environment

<?php

// Get the current default response codevar_dump(http_response_code());

http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method.

In summary - The differences between "http_response_code" and "header" for setting response codes:

1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.

@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().