PHP header() Function

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’);
}
?>

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.