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; 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 slight modification (yes, I know you aren't supposed to alter the Core files, however, I didn't believe that this tiny modification required making a completely new file)

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.

For my solution I replaced the above 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 )
        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