How to Make a PHP Redirect to a Different Page [Quick & Easy]

How to Make a PHP Redirect

Being able to redirect the user to a different page in PHP can be useful if you’ve moved a page to a different location or want to send the user elsewhere – directing them to an access denied or error page instead of the page they were trying to access.

This can be easily done using the PHP header() function.

Using the PHP header() Function to Redirect to a Different Page

To redirect the user to a different page, simply include the following PHP code:

header("Location: https://linuxscrew.com/");
die();

There are some things to keep an eye out for when doing this:

  • There can be no output prior to calling the header() function
    • header() MUST be called before any content is outputted to the page, be it HTML, text, blank lines, or other output from PHP
  • It is best to run die() after header() has been called to make sure no further content is rendered or no further code is partially executed, especially if you are redirecting away from sensitive content
  • The URL supplied can be relative, or link to an external site (In this example, it redirects to this very website)

For full details of what you can do with the header() function, check the official documentation:

https://www.php.net/manual/en/function.header.php

For more short and sweet PHP articles, check out our PHP category.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *