PHP Function Reference

PHP http_response_code() Function



The PHP http_response_code() function is used to get or set the HTTP response status code.

Syntax

http_response_code(response_code)

Parameters

response_code Optional. Specify a response code (like 404).

Return Value

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.

Returns false if response_code is not provided and it is not invoked in a web server environment (such as from a CLI application). Returns true 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).

Example: using http_response_code() in a web server environment

The example below shows the usage of http_response_code() function in a web server environment.

<?php
//getting the current response code and 
//set a new response code
var_dump(http_response_code(404));

//getting the new response code
var_dump(http_response_code());
?>

The output of the above code will be:

int(200)
int(404)

Example: using http_response_code() in a CLI environment

The example below shows the usage of http_response_code() function in a CLI environment.

<?php
//getting the current default response code
var_dump(http_response_code());

//setting a response code
var_dump(http_response_code(201));

//getting the new response code
var_dump(http_response_code());
?>

The output of the above code will be:

bool(false)
bool(true)
int(201)

❮ PHP Network Reference