How to redirect in PHP 8

Description

Redirecting a http request to another location is one of the most common http operations. Be it, a website was moved to a new location or an API endpoint is served from somewhere else. Redirects are part of the bread and butter of the world wide web.

Before we can redirect a request, we first have to understand how a redirect works in HTTP before we can use PHP 8's header function to redirect a request. As I've already alluded, a request can only be redirected if a server returns a special header that indicates to the client where it should be redirected to.

Location header

The location response header tells the client where to send the next request. But, the client only respects this header if the status code of the response is any of the following: 301, 302, 303, 307, or 308. Beneath you can see an example location header that would tell the client to redirect to the location /home.

Location: /home

Since the location header is part of the header section in the http response, you have to make sure that PHP does not return a HTTP body before you set the location header. Otherwise the request may not be redirected.

In PHP 8 you have to use the header function to redirect the client. The function signature looks like this:

header(string $header, bool $replace = true, int $response_code = 0): void

The header function has one mandatory $header parameter. It constitutes the raw header that should be delivered to the client. The $replace parameter indicates whether or not a previously defined header with the same key should be replaced or another instance with the same key should be set in the response. Lastly, the $response_code parameter indicates which response code should be used in case it hasn't been set already.

PHP 8 header redirect

Here are several examples on how you'd be able to a redirect to /home as in the example above:

header("Location: /home");

In this example a redirect status code of 302 is implied by PHP.

header("Location: /home", true);

In this example a redirect status code of 302 is implied by PHP and the previously set location header is replaced by the given one. PHP sends the same header as above.

header("Location: /home", true, 301);

header("Location: /home", true, 302);