The following is a function to redirect to a new URL. It will use either a header() call or output javascript, a meta refresh, and a link depending on whether output has been started. It will also intelligently fix your URL to make it absolute (the Location header technically requires an absolute URL).
function redirect($url = false) { if (empty($url) || substr($url, 0, 4) !== 'http') { $url = 'http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 's' : '').'://'.$_SERVER['HTTP_HOST']. (!empty($url) && $url[0] == '/' ? '' //if the URL is already from the root : (empty($url) || $url[0] == '?' ? $_SERVER['PHP_SELF'] //if the url is empty or starts with ?, prefix with current dir & script : dirname($_SERVER['PHP_SELF']).'/')). //if the url is not empty and does not start with ?, add current dir $url; } if ((stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE') && stristr($_SERVER['HTTP_USER_AGENT'], 'Mac')) || headers_sent()) { echo '<script language="JavaScript1.1"> <!-- location.replace("'.$url.'"); //--> </script> <noscript> <meta http-equiv="Refresh" content="0; URL='.htmlentities($url, ENT_QUOTES).'"/> </noscript> Please <a href="'.htmlentities($url, ENT_QUOTES).'">click here</a> to continue. '; } else { header('Location: '.$url); header('Connection: close'); } exit; }
There are also a few other peculiarities above. First off the header() call is never used for IE:mac. It doesn't handle header redirects well. (Of course this browser is very old and unmaintained, but I included it for completeness.) The Connection: close is also sent when header() is used to stop IE from trying to use keep-alive when it is redirected from http to https or vice-versa.
/** * does a regular split, but also accounts for the deliminator to be within quoted fields * for example, if called as such: * splitQuoteFriendly(',', '0,1,2,"3,I am still 3",4'); * it will return: * array(0 => '0', * 1 => '1', * 2 => '2', * 3 => '"3,I am still 3"', * 4 => '4'); * @param string deliminator to split by * @param string text to split * @param string text which surrounds quoted fields (defaults to ") * @return array array of fields after split */ function splitQuoteFriendly($delim, $text, $quote = '"') { $strictFields = explode($delim, $text); for($sl = 0, $l = 0; $sl < sizeof($strictFields); ++$sl) { $fields[$l] = $strictFields[$sl]; $numQuotes = 0; while(fmod($numQuotes += substr_count($strictFields[$sl], $quote), 2) == 1) { ++$sl; $fields[$l] .= $delim.$strictFields[$sl]; } ++$l; } return $fields; }