When to Use a PHP Header Redirect
Friday, November 25th, 2011
PHP, as well as other programming languages, have the ability to interact directly with the HTTP Headers.
The HTTP Headers are a separate part of the request/response body. This separation is typically a blank line. The headers provide various information. This is the place where the information type is defined (text/plain). The headers can also contain many other data points, such as the language, charset, encoding, cache-control, content length and more.
The important thing to remember is that the header is sent separately from the request or the response body. The body contains the actual data.
This is important because there will be times when you need to perform a certain action that requires the user be ‘redirected’ to another web page, or even another web site. Before all the body information is passed along through HTTP. This will save bandwidth and make your application faster.
A header redirect is common when a user does not have the privileges for a certain section of a website. As an example think of your online banking account. You must be logged in before you can see your own account information. If you try to see your data without being logged in, the web server will redirected you to the login page.
In PHP you can interact directly with the headers of HTTP. If you find that a user does not have the right credentials in a session store ($_SESSION), then that user can be redirected to another page.
This is done with the PHP header() function.
Line 1:
In line 2 above, the session information is checked to see if a session array key ‘user_credential’ exists, and is not already equal to ‘admin’. If the session key doesn’t equal admin, the header function is called and the page is redirected to the login.php page. This ensures that the user won’t be able to see critical information with permission.
Note: The session key is set when the user logs in correctly after submitting the login form. It will be empty if they have not logged in yet.
PHP headers are a very quick and efficient way to change the flow of a program. They are typically called when a users doesn’t have the correct credentials or privileges.









