How to Set Status Codes in PHP: A Practical Guide

Learn how to set HTTP status codes in PHP using header and http_response_code, with examples for 200, 301, 404, and 500. Includes testing tips, edge cases, and best practices for APIs and web apps.

Why Error Code
Why Error Code Team
·5 min read
PHP Status Codes - Why Error Code
Photo by doki7via Pixabay
Quick AnswerSteps

To set an HTTP status in PHP, use header('HTTP/1.1 404 Not Found') or http_response_code(404). These calls must occur before any output. For API endpoints or web pages, sending the correct status code communicates the result to clients and search engines. This quick answer covers the essential commands and common use cases in practice.

Understanding HTTP status codes in PHP

HTTP status codes are part of the HTTP response header that tells the client what happened with their request. In PHP, the server constructs this header, and PHP provides two primary tools: header() and http_response_code(). The phrase "how to set status code in php" is a common developer question because incorrect status codes lead to poor UX, SEO issues, and silent failures. In practice, always set the status before output, and ensure that your application logic maps errors to meaningful codes (200 for success, 400 for client errors, 404 when something is missing, 500 for server errors). Beginners should remember that headers must be sent before any content is echoed or flushed. When building APIs, prefer explicit JSON payloads with a matching status code to help clients handle responses correctly.

PHP
<?php // Tiny example: force a 200 OK http_response_code(200); echo 'OK'; ?>
PHP
<?php // Example: set a 404 Not Found header and a message header('HTTP/1.1 404 Not Found', true, 404); echo 'Resource not found'; ?>

Notes: If you already started output, header() may fail. Use output buffering or place header calls early in the request handling path. For RESTful APIs, always align your status codes with the action performed and the data returned.

languageOverridesEnabledIfNeeded

Steps

Estimated time: 20-35 minutes

  1. 1

    Identify endpoint semantics

    Map each API/route to the status code you expect on success and failure.

    Tip: Define a consistent mapping before coding.
  2. 2

    Choose your method

    Decide between http_response_code() or header() for your status updates.

    Tip: Prefer http_response_code() for simple codes.
  3. 3

    Implement in code

    Add status-setting calls at the beginning of request handlers, before output.

    Tip: Avoid sending output before headers.
  4. 4

    Return a payload

    When sending JSON, set Content-Type before echoing, and include a code field if needed.

    Tip: Keep the payload aligned with the status.
  5. 5

    Test with curl

    Curl the endpoint and inspect HTTP status line and body.

    Tip: Use -i to view headers.
  6. 6

    Review edge cases

    Test redirects, client errors, and server errors; ensure proper messaging.

    Tip: Document status codes in your API docs.
Pro Tip: Always set Content-Type before writing the body.
Warning: Do not send multiple conflicting status codes for a single response.
Note: Headers must be sent before any output; use output buffering if needed.

Prerequisites

Required

Commands

ActionCommand
Start PHP built-in serverRun from project root; ensure index.php existsphp -S localhost:8000 -t public
Test endpoint from CLIRequires running servercurl -i http://localhost:8000/endpoint
One-liner to set a status in PHPDemonstrates status change in CLIphp -r 'http_response_code(418); echo 418;'

Frequently Asked Questions

What is the difference between header() and http_response_code() in PHP?

header() sends a full HTTP header string and can set a code as the third parameter, while http_response_code() updates only the numeric status. Use header() when you need a detailed reason phrase (like 301 Moved Permanently).

Use header() when you need custom status phrases; http_response_code() for simple, explicit codes.

Can I set status codes after output has started?

Generally no. PHP sends headers before the body, so trying to set a status after output has begun will often fail unless output buffering is enabled. Plan headers early.

You usually can’t change the status after output begins unless you buffer output.

Should API responses always include a body?

Not always. A 204 No Content can accompany an empty body. For errors, include a JSON payload with an error code and message to help clients handle the failure.

Sometimes the status alone is enough, but most APIs return a body with details.

How do I perform a redirect with a status code?

Use header('Location: /new-path', true, 301) and exit; The client will receive a redirect with the specified status.

Redirects are done with a Location header and a 3xx code.

Is 418 a real status code?

Yes, 418 is part of the HTTP status code registry ('I'm a teapot'), though it’s rarely used in production. Use standard codes for clarity.

418 exists, but use common codes for production APIs.

Top Takeaways

  • Set status codes early in the request.
  • Use http_response_code() for simple updates.
  • Match codes with RESTful semantics.
  • Test with curl to verify headers and payload.

Related Articles