How to Make a Redirect with the PHP header() Function

09/04/2021

Contents

In this article, I will introduce how to make a redirect with the PHP header() function.

PHP header() Function

You can use the header() function to redirect a user to another page.

This function is used, for example, when a user accesses a page that requires login, and if the user is not logged in, redirects to the page where the ID and password are entered.

Syntax:

header("Location: http://www.example.com/");

The method of writing the code is as above, and it is specified as Location: URL of the transition destination.

This URL can be specified as either an absolute path starting with “http://” or a relative path starting with “./”.

Sample

<?php
  header("Location: https://plantpot.works/");
  exit();
?>

The exit() must be specified to end the process.

Note that if you put echo, print, HTML, line feed, etc. before the header() function as shown below, an error will occur.

<p>Hello World!</p>
<?php

  header("Location: https://plantpot.works/");
  exit();
?>

Also be careful if there is a space before the php tag.
If there is a space before “?php” at the beginning of the code, it will be regarded as outputting HTML and processing will not work properly.
So make sure there are no unnecessary line breaks or spaces.