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: