Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

Example 2 – Return a 400 status code

http_response_code(400);
exit;

See the HTTP response below

Example 3 – Return a 301 status code

http_response_code(301);
exit;

See the HTTP response below

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.

The post How To Return HTTP Status Codes In PHP appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

How To Return HTTP Status Codes In PHP

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×