PHP Header Redirection Not Working

somavian

New Member
Messages
7
Reaction score
0
Points
0
I'm using the PHP Header function to redirect to another page after doing some checks, but the redirect isn't working correctly, it just refreshed to an almost completely blank page of the same name (it includes and <link> and <script> in <head>, <body is empty). My redirect function looks like these (I've tried all of them):

PHP:
<?PHP function redirect($url){header("location: ".$url); exit;} session_start();?> //$url = index.php

<?PHP function redirect(){header("location: http:\\www.google.com"); exit;} session_start();?>

<?PHP function redirect(){header("location: http:\\www.*myOwnSite*.ca"); exit;} session_start();?> //*myOwnSite* is actually something else, but it's still my own site hosted elsewhere.
I've put all of these attempts at the very top of the page and have tried them on different pages. Also, another thing to note is that all these of these work on another host as well as my own personal one.

Once last note, while the function is declared at the top, it's actually called from further in. I wasn't sure if this was important as it has worked for me as is on other hosts.
 
Last edited:

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
"Called from further in" is probably your problem; you're very likely sending headers before your code gets here. That will work if output buffering is turned on at the server (or account) level, ut output buffering is off here. You would need either to make sure that the header info is the first thing sent, or use ob_start() at the beginning f your script in order to ensure that nothing is sent until your headers have been prepared. See the PHP manual for usage (you'll also need to flush the buffer, etc., and that's all linked in the manual).
 

somavian

New Member
Messages
7
Reaction score
0
Points
0
That worked, thanks for the reference.

Updated Code:
PHP:
<?PHP function redirect($url){header("location: ".$url); exit;} ob_start("redirect"); session_start();?>
//...
<?PHP redirect($url); ob_end_flush();?>

EDIT: That worked once the page was already loaded, but it stops the rest of the page from loading, is there any way to get around that?

EDIT2: ob_end_flush() needs to go at the end of the file.
 
Last edited:
Top