Skip to content

Show Output and Redirect No JS

Derek Jones edited this page Jul 5, 2012 · 5 revisions

In a project I am working on I wanted to be able to do a redirect that would allow output to be displayed to the user before redirecting; but I didn't want to use Javascript.

The CI redirect function in the URL helper did the majority of the work; all I had to do was make a couple of slight modifications.

As you can see in the original code

if ( ! function_exists('redirect'))
{
    function redirect($uri = '', $method = 'location', $http_response_code = 302)
    {
        if ( ! preg_match('#^https?://#i', $uri))
        {
            $uri = site_url($uri);
        }
        
        switch($method)
        {
            case 'refresh': header("Refresh:0;url=".$uri);
                break;
            default: header("Location: ".$uri, TRUE, $http_response_code);
                break;
        }
        exit;
    }
}

The function simply exits the entire script and doesn't allow for you to show any output, nor give it any kind of delay.

For my solution I created MY_url_helper.php in applications/helpers with the following:

/**
 * Header Redirect
 * 
 *
 * Header redirect in two flavors
 * For very fine grained control over headers, you could use the Output
 * Library's set_header() function.
 *
 * @access    public
 * @param    string    the URL
 * @param    string    the method: location or redirect
 * @param    int    the response code to be sent to the browser
 * @param    int    time in seconds to delay the redirect
 * @param    bool    true/false if the function should exit the CI kernel
 * @return    string
 */

if ( ! function_exists('redirect')) {
    function redirect($uri = '', $method = 'location', $http_response_code = 302,$time=0,$exit=true) {
    if ( ! preg_match('#^https?://#i', $uri)) {
        $uri = site_url($uri);
    }
    
    switch($method) {
        case 'refresh':
            header("Refresh:$time;url=".$uri);
        break;
        default: header("Location: ".$uri, TRUE, $http_response_code);
        break;
    }
    if($exit === false) // i chose to use false here to make sure the programmer actually enters false in the function call.
        return;
    else
        exit;
    }
}

Simple enough. By default the function will redirect in 0 seconds, exit and not break any existing usage. My desire for this functionality came from wanting to forward a user automatically to their control panel the first time they ever logged into my site, while also giving them the ability to override that by clicking elsewhere on the page.

Clone this wiki locally