+3 votes
in Web & Google by (3.7k points)

I added header("Location: $new_url",TRUE,301); to my php code to redirect an old page to a new URL, but I am getting “Headers already sent” error. How can I fix the error?

1 Answer

0 votes
by (11k points)

I was also getting the same error after adding header function to redirect one of my webpage. There are several ways to fix this error, such as add RedirectRule to .htaccess, use window.location function of javascript. But I fixed it by adding a print statement after header function. Seems it flushed the header information and hence the error was fixed. My code is as follows:

$url_elems = explode("/", $_SERVER['REQUEST_URI']);

if (count($url_elems) > 4){

$new_url = 'http://' . $_SERVER['SERVER_NAME'] . '/' . $url_elems[1] . '/' . $url_elems[2] . '/' . $url_elems[3];

header("Location: $new_url",TRUE,301);

exit;

}

print ''; //clear header that was already sent

I have exit function after header function and then print statement to flush the header information. Hope it helps.

...