How To Return HTTP Status Codes In PHP

The answer: Use the http_response_code() function with the relevant HTTP status code parameter.

Luckily for us, PHP has many inbuilt native functions that are great for the web. This is certainly one of them, using the function described above, we can issue 404, 400, 301, 200, and other statuses in one line of code.

Using http_response_code() in PHP

Example 1 – Return a 404 Status

http_response_code(404);
exit;

Now let’s check what the response looks like using an application like PostMan

404 status code response php

Example 2 – Return a 400 status code

http_response_code(400);
exit;

See the HTTP response below

400 status code response php

Example 3 – Return a 301 status code

http_response_code(301);
exit;

See the HTTP response below

301 status code response php

Code Breakdown –

  • We call to the http_response_code() function, passing in the status code in the style of an int
  • We then exit the script before any other unwanted behaviors take place, potentially preventing the response treated as a 200 OK status.

And that is it, hope this helps! For more information on the function used within this tutorial, you can check out the PHP documentation here.

Posted in PHP

Leave a Reply

Your email address will not be published.