PHP Safe Redirect Function

Posted on December 8th, 2011 by Wayne May in PHP | 0 comments

I see PHP code every day making use of the header function. Its the standard way to make redirects in PHP, but will fail if ANY output was sent to the browser before its called. There is a safer way to do this, which use JavaScript and meta redirects as a fail safe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    /**
     * Do a Safe Redirect
     *
     * This function will first try to do a server-side redirect, if it is not possible, if will fall back to a
     * Javascript redirect, if that fails, it will try a HTML redirect.
     * @param $url
     */
    function safe_redirect($url, $method = 'PHP')
    {
        try
        {
            if (!headers_sent())
            {
                //If headers are not sent yet... then do a php redirect
                @header('Location: '.$url);
                exit;
            } else throw new Exception();
        }
        catch( Exception $ex )
        {
            //If headers are sent... do a JavaScript redirect...
            //if javascript disabled, do html redirect.
            echo '<script type="text/javascript">';
            echo 'window.location.href="'.$url.'";';
            echo '</script>';
            echo '<noscript>';
            echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
            echo '</noscript>';
            exit;
        }
    }

Basically, this will check to see if headers were sent, if not, it will allow for a PHP header redirect, If output were set, it will make use of JavaScript, and, as a backup if JavaScript is not installed, it will cause a meta redirect.

Post a comment

Hello guest, care to post a comment?