How to Redirect to Another Web Page in PHP?

In PHP, you can use the Location header to redirect to another resource/web page. For example:

header('Location: https://www.google.com');
exit();

Please note that adding an exit() (or die()) right after the Location header is important to prevent further execution of the script.

The header() function also allows two additional (optional) arguments, and has the following signature:

header(string $header, bool $replace = true, int $responseCode = 0);
  1. $header — is the header string;
  2. $replace — boolean true or false to specify whether the header should replace a previous similar header or add a second header of the same type;
  3. $responseCode — HTTP response status code.

Please be aware that by default, using the Location header will return a status code of 302 to the browser (unless a 201 or a 3xx status code has already been set). You can change that to any other http status code for redirection by specifying the response status code as the third argument to the header() function. For example:

header('Location: https://www.google.com', true, 307);
exit();

Hope you found this post useful. It was published . Please show your love and support by sharing this post.