How to redirect using PHP with code examples

It’s often useful to redirect users to a different page after they submit a form or perform some other action on your website.

To redirect a user to a new page using PHP, you can use the header() function and specify the Location header with the URL of the page you want to redirect the user to.

Consider the example below:

  // redirect the user to the thank you page
  header("Location: thanks.php"); 
  // make sure any code below does not get executed

It’s important to note that the header() function must be called before any output is sent to the browser.

The exit function can be called so that any code below the header() function doesn’t get executed.

If you are redirecting to a different domain, you need to specify the absolute URL to the new domain:

  // redirect the user to a new domain

You can also specify a status code with the header function to indicate the type of redirect that’s being performed.

For example, to perform a permanent redirect (status code 301), you can use the following code:

  // redirect the user to the new domain permanently
  header("Location:", true, 301);

Finally, you redirect to a file with another extension.

For example, here’s how to redirect to a .html file:

  // redirect the user to a file

You can redirect to files of any type: .html, .php, .js, .png, .jpg, .mp3, .mp4, etc.

I hope this helps you get started with redirecting users to a new page with PHP. Nice work!

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.