Codeigniter & PHP - forcing a 404?

42,433

Solution 1

show_404() actually sends the proper headers for a search engine to register it as a 404 page (it sends 404 status).

Use a Firefox addon to check the headers received when calling show_404(). You will see it sends the proper HTTP Status Code.

Check the default application/errors/error_404.php. The first line is:

<?php header("HTTP/1.1 404 Not Found"); ?>

That line sets the HTTP Status as 404. It's all you need for the search engine to read your page as a 404 page.

Solution 2

        $this->output->set_status_header('404');

to generate 404 headers.

Solution 3

If you want a custom error page you can do the following thing.In your Libraries create a file name MY_Exceptions and extend it with CI_Exceptions.And then override the show_404() function.In this function you can now create an instance of your Controller class using &get_instance() function.And using this instance you can load your custom 404 Error page.

class MY_Exceptions extends CI_Exceptions {

public function __construct(){
    parent::__construct();
}

function show_404($page = ''){ // error page logic

    header("HTTP/1.1 404 Not Found");
    $heading = "404 Page Not Found";
    $message = "The page you requested was not found ";
    $CI =& get_instance();
    $CI->load->view('/*Name of you custom 404 error page.*/');

}

Solution 4

Only follows these steps:

Step 1 Update your application/config/routes.php file

$route['404_override'] = 'error/error_404';

Step 2 Create your own controller in controllers folder ex. error.php

<?php
class Error extends CI_Controller
{
function error_404()
{
    $data["heading"] = "404 Page Not Found";
    $data["message"] = "The page you requested was not found ";
        $this->load->view('error',$data);
}
}
?>

Step 3 Create your view in views folder ex. error.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title><?php echo $heading;?></title>
</head>

<body>
<?php echo $message;?>
</body>
</html>

Solution 5

I had the same problem with you and I found a complete solution for this in CodeIgniter 3. Here I would like to share step by step how to solve it. Of course, we need to support a custom 404 page to satisfy SEO requirement.

  1. Show 404 page for URLs which do not match the schema in routes
    • Add a new Error controller in application/controllers to support a custom 404 page.
class ErrorController extends CI_Controller 
{
    public function __construct() 
    {
        parent::__construct();
    } 

    public function index() 
    { 
        $this->output->set_status_header('404');
        return $this->load->view('errors/error_404'); 
    } 
}
  • Add a new custom view error_404.php for 404 page in application/views/errors
<div>
    <p>We are so sorry. The page you requested could not be found.</p> 
</div>
  • Declare 404_overide in config/routes.php
$route['404_override'] = 'ErrorController';
  1. Show 404 page for URLs which match the schema in routes but point to non-existing resource.
    • Set subclass_prefix in config/config.
$config['subclass_prefix'] = 'MY_';
  • Define your custom Exceptions class in application/core
class MY_Exceptions extends CI_Exceptions {

    public function __construct() {
        parent::__construct();
    }

    function show_404($page = '', $log_error = TRUE) {
        $CI = &get_instance();
        $CI->output->set_status_header('404');
        $CI->load->view('errors/error_404');
        echo $CI->output->get_output();
        exit;
    }

}
  • Call show_404() wherever you want. Here I created my custom supper model class in application/models and check query results there. Other models will extends the supper model and show 404 page if they could not found a resource.
abstract class MY_Model extends CI_Model
{

    protected $table = 'table_name';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function find($id)
    {
        $result = $this->db->get_where($this->table, ['id' => $id]);
        $data = $result->row_object();

        if (!$data) {
            show_404();
        }

        return $data;
    }
}
Share:
42,433
oym
Author by

oym

Updated on March 01, 2020

Comments

  • oym
    oym about 4 years

    In codeigniter, as you know, a page of the form: /class/function/ID, where class is the controller name, function is the method within the controller, and ID is the parameter to pass to that method.

    The typical usage would be (for a book site for example) to pass the book id to the function which would then query the database for appropriate book. My problem is this: I was messing around and randomly (in the url string) typed in an ID that is not present in the database (with normal point and click browsing this would never happen) and I get database errors due to the residual queries I attempt to perform using a non-existent ID.

    I have written code to check if there are any rows returned before attempting to use the ID, but if the ID is non-existent I would like the user to get a 404 error page rather than a blank page or something (since this seems like proper functionality). This would need to be a true 404 page (not simply loading a view that looks like a 404 page) so as not to screw with search engines. Okay - so my question is this: within normal program logic flow (as described above) how can I force a 404 error using codeigniter? Thanks.

    Update: code igniter has a show_404('page') function but I don't think this will generate a true HTTP 404 error...