HTTP Redirects with plain PHP

June 16, 2022  ‐ 3 min read

With PHP we can redirect the user to a different website or URL by means of the Location HTTP header. This response header gives an indication to the browser where to redirect the user to.

In order to send back HTTP headers in PHP we need the built-in header() network function of PHP. This function allows you to send back a raw HTTP header.

As mentioned above we set the HTTP headers raw, so we don't separate the header name and value as a key-value pair or so. Instead we set both the name and value in a single string.

This looks like the following in a PHP script:


Do make sure that you don't write any output to the browser before setting the header, otherwise the script will fail.

Redirect with response code

PHP is smart enough to change the HTTP response status code for you when you set the Location header. Instead of a regular 200 response the code 302 is returned to indicate a redirect.

However, we set a different response code if we find another more suitable. For example:

  • 301 to indicate that the location of the requested resource has been changed permanently.
  • Or 307 to indicate a temporarily moved resource.

We can set the response code as the third argument to the header() function.

// HTTP 301 - Moved Permanently
header('Location:', true, 301);

The response code is the third argument to the header() function, we can pass the response code as an integer. The second argument in the replace option which defaults to true when not set manually. It indicates whether the header should be replaced if it has been set already.

Redirect HTTP to HTTPS

Probably a more suitable place to redirect HTTP traffic to HTTPS is in the webserver configuration. But, if necessary, a redirect in PHP does the job too.

First, make sure you only redirect to HTTPS if you are on actually on HTTP. To prevent your script from getting in an infinite redirect loop (ERR_TOO_MANY_REDIRECTS).

Second, we can get the current host with URI from the $_SERVER automatic global variable. This we can use to redirect to HTTPS.

if (!isset($_SERVER['HTTPS']))
    $currentUrl =  "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    header("Location: https://{$currentUrl}");

Redirect to relative URI

Besides redirects to absolute URIs it is perfectly legal to redirect to relative URIs as well. This allows you to redirect traffic to a different page on the same website.

In this case we only need to pass the path as the header value.

header('Location: /home');