W3docs

PHP http_response_code() Function

Use PHP's http_response_code() to set or get HTTP status codes (404, 301, 500), handle redirects, and avoid the headers-already-sent pitfall.

Every HTTP response a server sends carries a status code — a three-digit number that tells the browser (or API client) whether the request succeeded, was redirected, or failed. PHP's built-in http_response_code() function, added in PHP 5.4, lets you read or set that code with a single call. It's the simplest, most portable way to return a 404 Not Found, a 301 redirect, a 403 Forbidden, or any other status from a PHP script.

This chapter covers the syntax, how to get vs. set the current code, the most common codes you'll use, the output-buffering gotcha that trips people up, and how http_response_code() compares to setting the status line by hand with header().

What http_response_code() does

http_response_code() has two modes depending on whether you pass an argument:

  • Set modehttp_response_code(404) sets the response status code to 404.
  • Get modehttp_response_code() (no argument) returns the current status code as an integer, or false (in CLI it returns true/false) if no code has been set yet in a web context.

It only touches the status code itself. It does not send a body, redirect the browser, or print an error page — that's still your job.

Syntax

http_response_code(int $response_code = null): int|bool
ParameterDescription
$response_codeOptional. The status code to set (e.g. 200, 404, 500). Omit it to read the current code instead.

Return value: when setting, it returns the previous code (or 200 if none was set). When getting in a web context, it returns the current code. Outside a web server (CLI), it returns true after setting and false when reading with no code set.

Setting a status code

The classic use is returning a "not found" response from a router or a missing-page handler:

<?php
// Tell the client this page does not exist
http_response_code(404);
echo "Page not found.";

The 404 is written to the response header that goes out before the body, so the browser knows the request failed even though you still printed a message.

A 403 for a blocked resource looks the same:

<?php
if (!$userIsLoggedIn) {
    http_response_code(403);
    exit("Access denied.");
}

Reading the current status code

Call the function with no argument to find out what code the response currently carries — useful in shutdown functions, logging, or middleware:

<?php
http_response_code(404);

// Later in the same request:
$current = http_response_code();
echo $current; // 404

Redirecting with a status code

A redirect needs two things: the right status code and a Location header. Use http_response_code() for the code and header() for the destination:

<?php
// Permanent redirect to the new URL
http_response_code(301);
header("Location: https://www.w3docs.com/new-page");
exit;

Use 301 for a permanent move (search engines update their index) and 302/307 for a temporary one.

Common HTTP status codes

CodeMeaningTypical use
200OKSuccessful request (the default)
201CreatedA resource was created (POST to an API)
301Moved PermanentlyPermanent redirect
302FoundTemporary redirect
307Temporary RedirectTemporary redirect, method preserved
400Bad RequestMalformed input from the client
401UnauthorizedAuthentication required
403ForbiddenAuthenticated but not allowed
404Not FoundThe resource doesn't exist
500Internal Server ErrorUnhandled server-side failure

The "headers already sent" gotcha

Status codes live in HTTP headers, and headers must be sent before any output. If your script has already echoed HTML, printed a blank line, or even has whitespace before the opening <?php tag, the headers are already flushed and http_response_code() silently does nothing (PHP also emits a "headers already sent" warning).

<?php
echo "Hello";          // body sent → headers are now locked
http_response_code(404); // too late, has no effect

To check whether output has already gone out, use headers_sent():

<?php
if (!headers_sent()) {
    http_response_code(404);
}

Fixes for the common causes: remove stray whitespace before <?php, avoid echo/print before setting the code, or enable output buffering with ob_start() so output is held until you're ready.

http_response_code() vs. header()

Before PHP 5.4 you had to build the status line manually with header():

<?php
// The old way — still works, but verbose and you must repeat the protocol/text
header("HTTP/1.1 404 Not Found");

// The modern equivalent
http_response_code(404);

http_response_code() is preferred because it doesn't require you to hard-code the HTTP version or the status text, and it can also read the current code — something a raw header() call can't do. See header() and headers_list() for finer control over response headers.

Conclusion

http_response_code() is the cleanest way to read or set an HTTP status code in PHP. Remember the three things that matter in practice: call it before any output, pick the right code for the situation (404 for missing, 403 for forbidden, 301/302 for redirects), and pair redirects with a Location header(). To dig deeper into PHP's request/response tooling, explore PHP functions and the header() function.

Practice

Practice
Which of the following are valid HTTP response status codes for indicating redirections in PHP?
Which of the following are valid HTTP response status codes for indicating redirections in PHP?
Was this page helpful?