PHP header forwarding not working

If you are finding that header() is not working for no obvious reason, make use of the headers_sent() function to drill down to the cause of the problem.

Consider the following scenario,

1
2
3
4
5
6
7
<?php
// Sign out
signOut();
 
// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

If for some reason, the header() call to redirect is not working, there won’t be any error messages, making it difficult to debug.  However, using headers_sent(), you may easily find the source of the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// Sign out
signOut();
 
/*
* If headers were already sent for some reason,
* the upcoming call to header() will not work...
*/
if(headers_sent($file, $line)){
// ... where were the mysterious headers sent from?
echo "Headers were already sent in $file on line $line...";
}
 
// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

source (comment by jasper)

Leave a Reply

Your email address will not be published. Required fields are marked *