Browser redirect with PHP

Josh Sherman
1 min read
Software Development PHP

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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles