Redirecting in PHP

I mistakenly thought redirecting the user would be a simple and well documented process in php. NOT! I’ll get right to what actually works.

function redirect($url) {
 if (strlen($url) > 0) {
 if (headers_sent()) {
 echo "<script>document.location.href='" . $url . "';</script>";
 echo "<noscript><meta http-equiv="refresh" content="0;'" . $url . "'" /></noscript>";
 else {
 header("Location: " . $url);

The above block of code is placed in the header, and it contains 3 methods of redirection. I doubt the php “header()” option will work at all, but I left it in for completeness. header() has to run before ANYTHING else on the page does, and no matter how I put that in, it did not work in a situation where I needed to pass it $url.

The preferred method is to use that tiny bit of JavaScript, and I put META refresh in there as a backup for the odd situation when JavaScript is disabled.

Credit where credit is due:

Leave a Reply