PHP header() Function
The header() function sends HTTP response headers.
syntax:
————-
int header ( string string [, bool replace])
Example:
————–
header(”Location: http://www.mysite.com/homepage.php”);
Limits:
———
1. We have to use it before PHP has sent any output (and therefore its default headers).
Since the response headers are separated from the content by a blank line. This means we can only send them once, and if our script has any output (even a blank line or space before opening <?php tag), it shows “Warning: Cannot modify header information - headers already sent by…..”
For Example,
Welcome to my website!<br />
<?php
if($test){
echo “You’re in Home Page!”;
}
else{
header(’Location: http://www.mysite.com/login.php’);
}
?>
What this script is trying to do is redirect the visitor using the Location header if $test is not true.
The ‘Welcome…’ text gets sent no matter what, so the headers are automatically sent. By the time header() is called, it’s already too late:
instead of getting redirected, the user will just see an error message (or if error reporting off, nothing but the ‘Welcome…’ text).
To avoid this,
rewrite the code as,
<?php
if($test){
echo ‘Welcome to my website<br />You’re in homepage!’;
}
else{
header(’Location: http://www.mysite.com/login.php’);
}
?>
