Skip to content

PHP http_response_code() Function: Everything You Need to Know

As a PHP developer, you may need to set the HTTP response code for your web application. The http_response_code() function is a built-in function in PHP that allows you to set the HTTP response code. Introduced in PHP 5.4.0, this function is essential for handling redirects and error pages. In this article, we will take an in-depth look at the http_response_code() function and its usage.

What is the http_response_code() Function?

The http_response_code() function is a PHP built-in function that allows you to set the HTTP response code for your web application. When called without arguments, it returns the current HTTP status code.

How to Use the http_response_code() Function

Using the http_response_code() function is straightforward. Here is the syntax of the function:

The PHP syntax of http_response_code() Function

php
http_response_code(code);

The function takes one parameter:

  • code: The HTTP response code to be set.

Important: This function must be called before any output is sent to the browser (including HTML, blank lines, or echo statements), otherwise it will have no effect.

Here is an example of how to use the http_response_code() function to set the HTTP response code to 404:

Example: Setting a 404 Status Code

php
<?php
// Set the HTTP response code to 404 Not Found
http_response_code(404);
echo "Page not found.";
?>

In this example, we use the http_response_code() function to set the HTTP response code to 404. This code will be sent to the client when the script is executed.

Conclusion

The http_response_code() function is a useful tool for setting the HTTP response code in your PHP web application. By understanding the syntax, version requirements, and usage constraints, you can easily set the appropriate response code for your PHP application. We hope this article has been informative and useful in understanding the http_response_code() function in PHP.

Practice

Which of the following are valid HTTP response status codes for indicating redirections in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.