Within nearly every web site or application there is a need to redirect a user to another page. Perhaps you want to route them to a login page when they aren’t authenticated or maybe because a page moved and you want to take them to the new location. To accomplish this in PHP we need to make use of the header()
function to set the destination address in the HTTP headers.
For a simple redirect to another page on your site all you need to do is:
header('Location: /path/to/destination'
This also works when directing a user to page that isn’t part of your site:
header('Location: http://othersite/path/to/destination'
And for those scenarios where you want to alert the browser (and bots) that the location has moved permanently and alert them of the new location:
header('HTTP/1.1 301 Moved Permanently'
header('Location: http://newsite/path/to/destination'
That last example is great if you’ve moved a couple of pages and want to redirect them but I wouldn’t necessarily recommend it if you’ve migrated an entire site to a new domain. In that scenario I would perform the redirect with the web server’s rewrite functionality as it can be accomplished with a single rewrite line.