Case Case - 1 month ago 16
PHP Question

Header Redirect Conflict Confusion

I have read about 25 pages about this issue but no real clarity. More confusion than anything.

I have a redirect function I use below

function RedirectToURL($url){
return header("Location: {$url}");
exit();
}


then in my code when I want to redirect.

if (register($email, $username, $password)) {

set_message('<div class="alert-success" data-closable>
Account Registered.</div>');

RedirectToURL("index.php");

}


Now it registers the user but produces the following error,


Warning: Cannot modify header information - headers already sent


I have no white spaces or anything.. I read that redirects cause this issue.

My dilemma is that the posts i have read say using ob_start is a good idea, but i found some posts also that say ob_start is a bad idea. because ob_start will remove the error but the issue will still exist.

So by those post i am confused and not sure the correct way to resolve this.

Answer

If your function set_message() outputs passed parameter, headers already sent. You should not print anything before redirect. If you want to print some message after redirect, you can store it in $_SESSION on some key before redirect and output on the index page if the key exists.

Also, your exit() is unreachable. Remove return before header().

function RedirectToURL($url)
{
   header("Location: {$url}");
   exit();
}

if (register($email, $username, $password)) {
    set_message('<div class="alert-success" data-closable>Account Registered.</div>');

    RedirectToURL("index.php");
}

function set_message($message)
{
    $_SESSION['redirect_message'] = $message;
}

Some block on your index page:

if (array_key_exists('redirect_message', $_SESSION)) {
    echo $_SESSION['redirect_message'];
    unset($_SESSION['redirect_message']);
}