Tutorial : PHP Cannot modify header information
by toy
Reference : PHP Cookbook, O’REILLY
I don’t know that some of you have this problem for a long time like me. I have this problem when I want to redirect my PHP to another php page. I get this error. Warning: Cannot modify header information – headers already sent by (output started at / blah blah blah…
Well, the problem is you trying to redirect page in PHP, the Location goes with the header of the URL. If you also print something out on the page, you will get this error. So, put the header code at the top of the page before anything.
Redirect to a different location
Problem
You want to automatically send a user to a new URL. For example, after successfully saving from data, you want to redirect a user to a page that confirms that the data has been saved.
Solution
Before any output is printed, use header(). to send a Location header with the new URL and then call exit() so that nothing else if printed.
If you are trying to do something like this, you will get the error
1 2 3 4 5 6 7 8 9 | <?php session_start(); if( !isset( $_SESSION["username"] )) { echo "User : ".$_SESSION['username']; header( 'Location: http://www.example/index.php' ) ; exit(); } ?> |
Please be aware that Redirect URLs should include the protocol and hostname. They shouldn’t be just a pathname like this.
1 2 3 4 5 |
Twitter
Facebook