简体   繁体   中英

How to Custom 404 Page Not Found in CodeIgniter 4

I just learn CodeIgniter 4 Framework. How to customize my 404 page not found?

Go to your Routes.php file and find

$routes->set404Override();

Now, If you want to display just an error message then write

    $routes->set404Override(function(){
    echo "your error message";
});

instead of

$routes->set404Override();

Or If you want to return a view then write like below:

$routes->set404Override(function(){
    return view('your_filename');
});

instead of

$routes->set404Override();

// Would execute the show404 method of the App\Errors class

$routes->set404Override('App\Errors::show404');

// Will display a custom view

$routes->set404Override(function()
{
    echo view('my_errors/not_found.html');
});

To customize your 404 page, modify app/Views/errors/html/error_404.php to your liking.

For custom error messages

in Config\routes.php

// Custom 404 view with error message.
$routes->set404Override(function( $message = null )
{
    $data = [
        'title' => '404 - Page not found',
        'message' => $message,
    ];
    echo view('my404/viewfile', $data);
});

in my viewfile, to display error:

<?php if (! empty($message) && $message !== '(null)') : ?>
  <?= esc($message) ?>
<?php else : ?>
  Sorry! Cannot seem to find the page you were looking for.
<?php endif ?>

from my controller:

throw new \CodeIgniter\Exceptions\PageNotFoundException('This is my custom error message');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM