PHP: Send a 503 Service Temporarily Unavailable header.

This is a PHP tutorial on how to send a “503 Service Temporarily Unavailable” status code. This header can be useful to use if you are carrying out maintenance or a technical issue is currently preventing your app from working correctly.

By sending a 503 HTTP response code, we are letting the client know that something is “wrong” at the moment and that they should retry at a later stage. This header also helps prevent search engines from indexing broken web apps, etc.

Using PHP’s header function to respond with a 503 HTTP status code.

In this example, I will use PHP’s inbuilt header function to respond with a 503 HTTP status code:

In the PHP code above:

  1. We sent a “503 Service Temporarily Unavailable” status code to the client using PHP’s header function. Note that we used $_SERVER[“SERVER_PROTOCOL”] because we cannot assume that the client will be using HTTP/1.1. For all we know, they could be using HTTP/1.0
  2. We sent a Retry-After header to the client. This header tells the client how many seconds they should wait before trying again. Note that I emphasized the word “should” there because the client can simply ignore this header if they want to. Thankfully, bots and crawlers such as Googlebot will honor this header.
  3. Finally, we outputted a basic “under maintenance” message and exited the PHP script.

Note that if you do not provide a custom message, browsers such as Chrome will display the following message:

503 Chrome

Personally, I think that the 503 error message above is too uninformative.

Using the http_response_code function to return a 503 error.

If you are using PHP version 5.4.0 or above, then you can send a 503 response code using the aptly-named http_response_code function:

The code above works the exact same way as the PHP code in our first example. The only difference is that you don’t have to manually write out the full header details.

For other useful HTTP response codes, see:

Hopefully, you found this guide useful!

Facebook Comments