CodeIgniter Forums

Full Version: my approach to custom 404 errors - bypassing error_404.php without hacking or modifying the core
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]treehousetim[/eluser]
there has been a lot of discussion about this issue. I came up with a different approach from any I've run across.

first of all, I created a 404 controller. This I named f404 - it lives in the main controller folder.

Then in error_404.php, I removed everything in that except the header statement so my error_404.php file now looks like...
Code:
<?php header("HTTP/1.1 404 Not Found");

if ( function_exists( 'get_instance' ) )
{
    $ci = get_instance();

    $ci->load->view( 'template/top', array( 'title' => '404' ) );
    $ci->load->view( '404', array( 'msg' => '' ) );
    $ci->load->view( 'template/bottom' );
}
else
{
    global $CFG;
    readfile( $CFG->item( 'base_url' ) . 'f404/' );

in routes.php
Code:
$route['f404/(:any)'] = 'f404/index/$1';

in f404.php (the controller)
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class f404 extends controller
{
    function index( $msg = '' )
    {
        $this->load->view( 'template/top', array( 'title' => '404' ) );
        $this->load->view( '404', 'msg' => $msg );
        $this->load->view( 'template/bottom' );
    }
}

As you can see, I'm using fopen wrappers (allow_url_fopen in the ini) to stream the contents of the f404 controller back to the browser for errors. this way we still send the 404 header, the url doesn't change since we're not using 'location: ...' and you can utilize the methods you're already using for view/template management to display errors.

this seems to be working for me - feel free to use the code if you find it useful.

El Forum

[eluser]CoffeeBeanDesign[/eluser]
I like the simplicity of this method.

It works on my production server, however when I test on Xampp it crashes. Is there some issue with Xampp using readfile to load another page from localhost?? Is this something I should be wary of for production server too??

I have tested readfile on localhost with an external page and all works fine but any readfile("http://localhost... ) causes an Apache crash. file_get_contents on localhost does the same.

Any thoughts??