PHP redirect - How to send a redirect with PHP

PHP redirection FAQ: How can I redirect a user in a PHP script?

I've been working with OpenSSO a lot lately (Sun's open source identity management product), and one thing you see right away is that they redirect the user's browser a lot during the login process. During a typical login process a user will attempt to access a protected page; an OpenSSO agent will redirect the user's browser to the OpenSSO login page; and after a successful login they redirect you back to the protected resource.

As I try to mimic that behavior in my own custom PHP code, I quickly needed to learn how to redirect a browser from one PHP page to another.

Fortunately it's pretty easy. To redirect a browser from the current page to some other page (HTML, PHP, JSP, whatever), just use the PHP header function and the HTTP Location command. When you do this, you pass the Locationcommand and the URL of the destination HTML/PHP page as an argument to the header() function, like this:

header('Location: http://loginserver.example.com/login.php');

In the typical case you'll want this to be the only output you send to the user's browser, because when the browser receives this command it knows it is supposed to redirect to that page. Specifically, you don't want to write any raw text (plain text or HTML) to the browser before this, because that will generate the dreaded "headers already sent" error. (You can send other information with other calls to the header() method, but I haven't had any reason to do that yet.)

Also, note that the URL you pass with the Location command needs to be a complete URL, including the protocol (the http:// part).