Skip to content

Show Output and Redirect No JS

World Wide Web Server edited this page Jul 4, 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 [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;
}

}

[/code]

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: [code] 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;
}

} [/code]

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