Magento redirect

Sometimes there is a need to do a redirect from inside a Magento page where you might not know if headers are sent or not – Or maybe you wish to make a new redirect function where you don’t have to worry about writing different code if the headers are sent or not.

This is a way to do a redirect where a javascript redirect is used if headers have been sent (and thus it is no longer possible to use a header redirect)

if (!headers_sent()) {
	Mage::app()->getResponse()->setRedirect(Mage::getBaseUrl() . 'portal/');
else {
	$baseUrl = Mage::getBaseUrl() . 'portal/';
	print '<script type="text/javascript">';
	print "window.location.href = '{$baseUrl}';";
	print '</script>';

And the function headers_sent() is a php function so that can of course be used outside of Magento in any php scrip where a header location is nice but not always possible.