CodeIgniter builds error reporting into your system through Exceptions, both the SPL collection, as
well as a few custom exceptions that are provided by the framework. Depending on your environment’s setup,
the default action when an error or exception is thrown is to display a detailed error report unless the application
is running under the production
environment. In this case, a more generic message is displayed to
keep the best user experience for your users.
-
Using Exceptions
-
Configuration
-
Logging Exceptions
-
-
Framework Exceptions
-
PageNotFoundException
-
ConfigException
-
DatabaseException
-
RedirectException
-
-
Specify HTTP Status Code in Your Exception
-
Specify Exit Code in Your Exception
-
Logging Deprecation Warnings
Using Exceptions
This section is a quick overview for newer programmers, or for developers who are not experienced with using exceptions.
Exceptions are simply events that happen when the exception is “thrown”. This halts the current flow of the script, and
execution is then sent to the error handler which displays the appropriate error page:
<?php throw new Exception('Some message goes here');
If you are calling a method that might throw an exception, you can catch that exception using a try/catch
block:
<?php try { $user = $userModel->find($id); } catch (Exception $e) { exit($e->getMessage()); }
If the $userModel
throws an exception, it is caught and the code within the catch block is executed. In this example,
the scripts dies, echoing the error message that the UserModel
defined.
In the example above, we catch any type of Exception. If we only want to watch for specific types of exceptions, like
a UnknownFileException
, we can specify that in the catch parameter. Any other exceptions that are thrown and are
not child classes of the caught exception will be passed on to the error handler:
<?php try { $user = $userModel->find($id); } catch (CodeIgniterUnknownFileException $e) { // do something here... }
This can be handy for handling the error yourself, or for performing cleanup before the script ends. If you want
the error handler to function as normal, you can throw a new exception within the catch block:
<?php try { $user = $userModel->find($id); } catch (CodeIgniterUnknownFileException $e) { // do something here... throw new RuntimeException($e->getMessage(), $e->getCode(), $e); }
Configuration
By default, CodeIgniter will display all errors in the development
and testing
environments, and will not
display any errors in the production
environment. You can change this by setting the CI_ENVIRONMENT
variable
in the .env file.
Important
Disabling error reporting DOES NOT stop logs from being written if there are errors.
Logging Exceptions
By default, all Exceptions other than 404 — Page Not Found exceptions are logged. This can be turned on and off
by setting the $log
value of app/Config/Exceptions.php:
<?php namespace Config; use CodeIgniterConfigBaseConfig; class Exceptions extends BaseConfig { public $log = true; }
To ignore logging on other status codes, you can set the status code to ignore in the same file:
<?php namespace Config; use CodeIgniterConfigBaseConfig; class Exceptions extends BaseConfig { public $ignoredCodes = [404]; }
Note
It is possible that logging still will not happen for exceptions if your current Log settings
are not set up to log critical errors, which all exceptions are logged as.
Framework Exceptions
The following framework exceptions are available:
PageNotFoundException
This is used to signal a 404, Page Not Found error. When thrown, the system will show the view found at
app/Views/errors/html/error_404.php. You should customize all of the error views for your site.
If, in app/Config/Routes.php, you have specified a 404 Override, that will be called instead of the standard
404 page:
<?php if (! $page = $pageModel->find($id)) { throw CodeIgniterExceptionsPageNotFoundException::forPageNotFound(); }
You can pass a message into the exception that will be displayed in place of the default message on the 404 page.
ConfigException
This exception should be used when the values from the configuration class are invalid, or when the config class
is not the right type, etc:
<?php throw new CodeIgniterExceptionsConfigException();
This provides an exit code of 3.
DatabaseException
This exception is thrown for database errors, such as when the database connection cannot be created,
or when it is temporarily lost:
<?php throw new CodeIgniterDatabaseExceptionsDatabaseException();
This provides an exit code of 8.
RedirectException
This exception is a special case allowing for overriding of all other response routing and
forcing a redirect to a specific route or URL:
<?php throw new CodeIgniterRouterExceptionsRedirectException($route);
$route
may be a named route, relative URI, or a complete URL. You can also supply a
redirect code to use instead of the default (302
, “temporary redirect”):
<?php throw new CodeIgniterRouterExceptionsRedirectException($route, 301);
Specify HTTP Status Code in Your Exception
Since v4.3.0, you can specify the HTTP status code for your Exception class to implement
HTTPExceptionInterface
.
When an exception implementing HTTPExceptionInterface
is caught by CodeIgniter’s exception handler, the Exception code will become the HTTP status code.
Specify Exit Code in Your Exception
Since v4.3.0, you can specify the exit code for your Exception class to implement
HasExitCodeInterface
.
When an exception implementing HasExitCodeInterface
is caught by CodeIgniter’s exception handler, the code returned from the getExitCode()
method will become the exit code.
Logging Deprecation Warnings
New in version 4.3.0.
By default, all errors reported by error_reporting()
will be thrown as an ErrorException
object. These
include both E_DEPRECATED
and E_USER_DEPRECATED
errors. With the surge in use of PHP 8.1+, many users
may see exceptions thrown for passing null to non-nullable arguments of internal functions.
To ease the migration to PHP 8.1, you can instruct CodeIgniter to log the deprecations instead of throwing them.
First, make sure your copy of ConfigExceptions
is updated with the two new properties and set as follows:
<?php namespace Config; use CodeIgniterConfigBaseConfig; use PsrLogLogLevel; class Exceptions extends BaseConfig { // ... other properties public bool $logDeprecations = true; public string $deprecationLogLevel = LogLevel::WARNING; // this should be one of the log levels supported by PSR-3 }
Next, depending on the log level you set in ConfigExceptions::$deprecationLogLevel
, check whether the
logger threshold defined in ConfigLogger::$threshold
covers the deprecation log level. If not, adjust
it accordingly.
<?php namespace Config; use CodeIgniterConfigBaseConfig; class Logger extends BaseConfig { // .. other properties public $threshold = 5; // originally 4 but changed to 5 to log the warnings from the deprecations }
After that, subsequent deprecations will be logged instead of thrown.
This feature also works with user deprecations:
<?php @trigger_error('Do not use this class!', E_USER_DEPRECATED); // Your logs should contain a record with a message like: "[DEPRECATED] Do not use this class!"
For testing your application you may want to always throw on deprecations. You may configure this by
setting the environment variable CODEIGNITER_SCREAM_DEPRECATIONS
to a truthy value.
CodeIgniter lets you build error reporting into your applications using
the functions described below. In addition, it has an error logging
class that permits error and debugging messages to be saved as text
files.
Note
By default, CodeIgniter displays all PHP errors. You might
wish to change this behavior once your development is complete. You’ll
find the error_reporting() function located at the top of your main
index.php file. Disabling error reporting will NOT prevent log files
from being written if there are errors.
Unlike most systems in CodeIgniter, the error functions are simple
procedural interfaces that are available globally throughout the
application. This approach permits error messages to get triggered
without having to worry about class/function scoping.
CodeIgniter also returns a status code whenever a portion of the core
calls exit()
. This exit status code is separate from the HTTP status
code, and serves as a notice to other processes that may be watching of
whether the script completed successfully, or if not, what kind of
problem it encountered that caused it to abort. These values are
defined in application/config/constants.php. While exit status codes
are most useful in CLI settings, returning the proper code helps server
software keep track of your scripts and the health of your application.
The following functions let you generate errors:
-
show_error
($message, $status_code, $heading = ‘An Error Was Encountered’)¶ -
Parameters: - $message (mixed) – Error message
- $status_code (int) – HTTP Response status code
- $heading (string) – Error page heading
Return type: void
This function will display the error message supplied to it using
the error template appropriate to your execution:application/views/errors/html/error_general.php
or:
application/views/errors/cli/error_general.php
The optional parameter
$status_code
determines what HTTP status
code should be sent with the error. If$status_code
is less
than 100, the HTTP status code will be set to 500, and the exit
status code will be set to$status_code + EXIT__AUTO_MIN
.
If that value is larger thanEXIT__AUTO_MAX
, or if
$status_code
is 100 or higher, the exit status code will be set
toEXIT_ERROR
.
You can check in application/config/constants.php for more detail.
-
show_404
($page = », $log_error = TRUE)¶ -
Parameters: - $page (string) – URI string
- $log_error (bool) – Whether to log the error
Return type: void
This function will display the 404 error message supplied to it
using the error template appropriate to your execution:application/views/errors/html/error_404.php
or:
application/views/errors/cli/error_404.php
The function expects the string passed to it to be the file path to
the page that isn’t found. The exit status code will be set to
EXIT_UNKNOWN_FILE
.
Note that CodeIgniter automatically shows 404 messages if
controllers are not found.CodeIgniter automatically logs any
show_404()
calls. Setting the
optional second parameter to FALSE will skip logging.
-
log_message
($level, $message)¶ -
Parameters: - $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
- $message (string) – Message to log
Return type: void
This function lets you write messages to your log files. You must
supply one of three “levels” in the first parameter, indicating what
type of message it is (debug, error, info), with the message itself
in the second parameter.Example:
if ($some_var == '') { log_message('error', 'Some variable did not contain a value.'); } else { log_message('debug', 'Some variable was correctly set'); } log_message('info', 'The purpose of some variable is to provide some value.');
There are three message types:
- Error Messages. These are actual errors, such as PHP errors or
user errors. - Debug Messages. These are messages that assist in debugging. For
example, if a class has been initialized, you could log this as
debugging info. - Informational Messages. These are the lowest priority messages,
simply giving information regarding some process.
Note
In order for the log file to actually be written, the
logs/ directory must be writable. In addition, you must
set the “threshold” for logging in
application/config/config.php. You might, for example,
only want error messages to be logged, and not the other
two types. If you set it to zero logging will be disabled.
Обработка ошибок
CodeIgniter позволяет создавать отчеты об ошибках в приложениях, используя функции описанные ниже. Кроме того, он имеет класс ведения журнала ошибок, который позволяет сохранять ошибки и отладочные сообщения в виде текстовых файлов.
Примечание
По умолчанию, CodeIgniter отображает все PHP ошибки. При желании, вы можете изменить это поведение как только завершите разработку. Вы найдете error_reporting() функцию расположенную в верхней части основного файла index.php. Отключение отчетов об ошибках не помешает записывать лог файлы при возникновении ошибок.
В отличии от большинства систем CodeIgniter, функциям ошибок свойственны простые процедурные интерфейсы, которые глобально доступны для всего приложения. Этот подход позволяет получать сообщения об ошибках, не беспокоясь об обзоре класс/функция .
CodeIgniter также возвращает код состояния, всякий раз когда ядро вызывает exit(). Этот код состояния отличный от HTTP кода состояния, и уведомляет другие процессы был ли сценарий завершен успешно или нет, и что за проблема повлекла прерывание. Эти значения определены в application/config/constants.php. Эти коды состояния наиболее полезны при использовании CLI параметров, возвращаемых надлежащий код серверного обеспечения помогающий отслеживать ваши скрипты и состояние ваших приложений.
Следующие функции позволяют генерировать ошибки:
- show_error($message, $status_code, $heading = ‘Произошла Ошибка’)
-
Параметры: - $message (смешаный) – Сообщение об ошибке
- $status_code (число) – HTTP код состояния ответа
- $heading (строка) – Заголовок страницы с ошибкой
Возвращаемый тип: пустота
Эта функция отобразит сообщение об ошибке через шаблон ошибки, соответствующего вашему исполнению:
application/views/errors/html/error_general.php
or:
application/views/errors/cli/error_general.php
Необязательный параметр $status_code обозначает что код состояния HTTP должен быть отправлен с ошибкой. Если $status_code меньше 100, код состояния HTTP будет иметь значение 500, и выход кода состояния будет иметь значение $status_code + EXIT__AUTO_MIN. Если это значение больше, чем EXIT__AUTO_MAX, или $status_code 100 или выше, выход кода состояния будет установлен EXIT_ERROR. Вы можете ознакомиться в application/config/constants.php более подробно.
- show_404($page = », $log_error = TRUE)
-
Параметры: - $page (строка) – URI строка
- $log_error (булево (bool)) – Нужно ли регистрировать ошибки
Возвращаемый тип: пустота
Эта функция отобразит сообщение об ошибке 404 используя шаблон ошибки, соответствующего вашему исполнению:
application/views/errors/html/error_404.php
or:
application/views/errors/cli/error_404.php
Функция ожидает что ей передадут строку, являющуюся путем к файлу на ненайденную страницу. Выход кода состояния будет установлен в EXIT_UNKNOWN_FILE. Обратите внимание, CodeIgniter автоматически показывает ошибки 404 если контроллер не найден.
CodeIgniter автоматически регистрирует все show_404() вызовы. Необязательный второй параметр FALSE будет пропускать ведение журнала.
- log_message($level, $message, $php_error = FALSE)
-
Параметры: - $level (строка) – Уровень журнала: ‘ошибка (error)’, ‘отладка (debug)’ или ‘инфо (info)’
- $message (строка) – Сообщение журнала
- $php_error (булево (bool)) – Записывать ли родные сообщения об ошибках PHP
Возвращаемый тип: пустота
Эта функция позволяет записывать сообщения в лог файлы. Необходимо указать один из трех “уровней” первым параметром, указывая на тип сообщения (debug, error, info), с сообщением во втором параметре.
Example:
if ($some_var == '') { log_message('error', 'Some variable did not contain a value.'); } else { log_message('debug', 'Some variable was correctly set'); } log_message('info', 'The purpose of some variable is to provide some value.');
Существует три типа сообщений:
- Сообщения об ошибках. Эти фактические ошибки, такие как ошибки PHP или ошибки пользователя.
- Сообщения отладки. Это сообщения, которые помогают в отладке. Например, если класс был инициализирован, это может являться в качестве отладочной информации.
- Информационные сообщения. Они имеют самый низкий приоритет сообщений, просто давая информацию относительно некоторых процессов.
Примечание
Для того чтобы файл журнала на самом деле велся, категория logs/ должна быть доступна для записи. Кроме того, вы должны установить “порог” для ведения журналов application/config/config.php. Вы могли бы, например, записывать в журнал только сообщения об ошибках, а не двух других типов. Если вы установите его равным нулю, то ведение журнала будет отключено.
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…
asked Aug 6, 2009 at 3:01
0
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.
answered Aug 6, 2009 at 3:05
Andrew MooreAndrew Moore
92.4k30 gold badges163 silver badges175 bronze badges
4
$this->output->set_status_header('404');
to generate 404 headers.
answered Nov 15, 2013 at 0:13
JubairJubair
2,7293 gold badges29 silver badges27 bronze badges
0
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.*/');
}
answered Oct 26, 2010 at 8:55
sagar27sagar27
3,0813 gold badges26 silver badges36 bronze badges
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>
Bo Persson
89.8k31 gold badges144 silver badges201 bronze badges
answered Aug 20, 2011 at 11:16
NBNNBN
811 silver badge2 bronze badges
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.
- 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';
- 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;
}
}
answered Mar 1, 2017 at 4:25
Tung NguyenTung Nguyen
6977 silver badges6 bronze badges
Yes show_404() WILL send out a 404 but it looks like hell. There have been a few hacks suggested here, but why hack when you can use built in features?
Upgrade to CI 2.0 and you’ll be able to use the amazing:
$route['404_override'] = 'errors/error_404';
Then you can have a general errors controller without having to worry about trying to load views, libraries and helpers WY too early in the CI instance to function properly.
answered Oct 26, 2010 at 10:46
Phil SturgeonPhil Sturgeon
30.6k12 gold badges77 silver badges117 bronze badges
try using this
set_status_header(404);
answered Jul 26, 2013 at 9:23
GianFSGianFS
2,4652 gold badges22 silver badges21 bronze badges
Create controller in your application/controllers folder.
class Error extends Controller
{
function error_404()
{
$this->load->view('error');
}
}
Then in your application/library extend the Router class by creating application/libraries/MY_Router.php
class MY_Router extends CI_Router
{
private $error_controller = 'error';
private $error_method_404 = 'error_404';
function MY_Router()
{
parent::CI_Router();
}
// this is just the same method as in Router.php, with show_404() replaced by $this->error_404();
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if(file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if(is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if(count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if(!file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
return $this->error_404();
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if(!file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// Can't find the requested controller...
return $this->error_404();
}
function error_404()
{
$segments = array();
$segments[] = $this->error_controller;
$segments[] = $this->error_method_404;
return $segments;
}
function fetch_class()
{
// if method doesn't exist in class, change
// class to error and method to error_404
$this->check_method();
return $this->class;
}
function check_method()
{
$class = $this->class;
if (class_exists($class))
{
if ($class == 'doc')
{
return;
}
if (! in_array('_remap', array_map('strtolower', get_class_methods($class)))
&& ! in_array(strtolower($this->method), array_map('strtolower', get_class_methods($class))))
{
$this->class = $this->error_controller;
$this->method = $this->error_method_404;
include(APPPATH.'controllers/'.$this->fetch_directory().$this->error_controller.EXT);
}
}
}
}
If the page does not exist, it will be routed to error controller
answered Aug 23, 2009 at 3:44
1
404 Not Found is perhaps the most common type of error users encounter on the internet. It is one of the most common errors users experience during web browsing. Since the error could potentially impact the user experience, CMS and frameworks have come up with creative ways of handling the error.
Codeigniter offers a simple way of creating custom 404 error pages in which the website or the application could tackle the situation creatively and redirect the visitor to the appropriate page(s). This way, the developers have complete control over the user journey and could make sure that the visitor doesn’t bounce off the website. Codeigniter 404 Page Not Found error offers a great opportunity to retain user engagement and present related links and/or information about services or products to the visitors.
- Why 404 Not Found Error Occurs
- Create the Controller for Custom Codeigniter 404 Page Not Found Error
- Set up the Route
- Creating the View
- Alternative Method of Creating the Controller
- Conclusion
Why 404 Not Found Error Occurs
404 Not Found is the HTML error code that indicates a particular situation in which the connection between the server and the client is working correctly, but the server could not find the resource requested by the client.
The underlying causes of the error are several, but the general process is similar in all cases. The server has received a request for a resource that is non-existent on the server of PHP hosting. A very common cause of this situation is the broken links that point to pages or resources that have been removed (or taken down) by the website administrator.
In this article, I will show you how you can create a fully customized 404 error page in Codeigniter. I will start by creating the controller and then move on to set up the routes.
You might also like: Use Elasticsearch in Codeigniter
Create the Controller for Custom Codeigniter 404 Page Not Found Error
I will start by creating a class for the controller in the application/controllers/ folder . I have named this class My404 which has an index() method for loading the view.
<?php class My404 extends CI_Controller { public function __construct() { parent::__construct(); } public function index() { $this->output->set_status_header('404'); $this->load->view('err404'); } }
You might also like: Pass Data From Controller to View in CodeIgniter
Set up the Route
Next, I will set up the route in the application/config/routes.php file. This file will contain the following line that overrides the default route:
$route['404_override'] = 'my404';
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Creating the View
I will now describe the view of the custom 404 page in the application/views folder. you will notice that in the following complete code of the view that I have redirected the visitor to the homepage.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <?php $ci = new CI_Controller(); $ci =& get_instance(); $ci->load->helper('url'); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>404 Page</title> </head> <body> <div> <p>How to Create Custom Codeigniter 404 Error Pages </p> <div> <p><a href="<?php echo base_url(); ?>">Go Back to Home</a></p> </div> </div> </body> </html>
You might also like: Create Multiple Database Connections in CodeIgniter
Alternative Method of Creating the Controller
Another (and much simpler) way of creating a custom 404 page for your Codeigniter project is to add the following code to the system/application/controllers/error.php file. In this code, I have extended the controller class into a custom class named Error. This class contains the method error_404() that outputs the “404 – Not Found” error if it encounters the 404 code in the header.
<?php class Error extends Controller { function error_404() { $this->output->set_status_header('404'); echo "404 - not found"; } }
Now create MY_Router.php in the system/application/libraries/ folder and add the following code to it:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Router extends CI_Router { var $error_controller = 'error'; var $error_method_404 = 'error_404'; function My_Router() { parent::CI_Router(); } function _validate_request($segments) { if (file_exists(APPPATH.'controllers/'.$segments[0].EXT)) { return $segments; } if (is_dir(APPPATH.'controllers/'.$segments[0])) { $this->set_directory($segments[0]); $segments = array_slice($segments, 1); if (count($segments) > 0) { if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT)) { return $this->error_404(); } } else { $this->set_class($this->default_controller); $this->set_method('index'); if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT)) { $this->directory = ''; return array(); } } return $segments; } return $this->error_404(); } function error_404() { $this->directory = ""; $segments = array(); $segments[] = $this->error_controller; $segments[] = $this->error_method_404; return $segments; } function fetch_class() { $this->check_method(); return $this->class; } function check_method() { $ignore_remap = true; $class = $this->class; if (class_exists($class)) { $class_methods = array_map('strtolower', get_class_methods($class)); if($ignore_remap && in_array('_remap', $class_methods)) { return; } if (! in_array(strtolower($this->method), $class_methods)) { $this->directory = ""; $this->class = $this->error_controller; $this->method = $this->error_method_404; include(APPPATH.'controllers/'.$this->fetch_directory().$this->error_controller.EXT); } } } function show_404() { include(APPPATH.'controllers/'.$this->fetch_directory().$this->error_controller.EXT); call_user_func(array($this->error_controller, $this->error_method_404)); } }
Finally, I will call the 404 Page manually by calling the show_404() method that checks the two parameters passed in its array and shows error if it discovers that a parameter is missing. Use the following statement below to manually call the 404 Page.
$this->router->show_404();
Conclusion
In this short tutorial, I have demonstrated two methods that you can use for creating (and calling) a custom designed 404 error page for your Codeigniter application. A custom 404 error page is an ideal way of retaining visitors on the website and redirecting them to appropriate pages on the website. This greatly reduces the bounce rate of the websites and ensures that the visitors remain interested in your website. If you have further questions and queries about creating custom 404 pages for Codeigniter projects, do post them in the comments below.
Share your opinion in the comment section.
COMMENT NOW
Share This Article
Customer Review at
“Cloudways hosting has one of the best customer service and hosting speed”
Sanjit C [Website Developer]
Owais Alam
is the WordPress Community Manager at Cloudways — A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]
×
Get Our Newsletter
Be the first to get the latest updates and tutorials.
Thankyou for Subscribing Us!
CodeIgniter displays a simple 404 error page whenever the user navigates to a broken link.
You can easily customize it and make it more user-friendly for the user.
In this tutorial, I show how you can create a custom 404 error page in CodeIgniter 3.
Contents
- Route
- Controller
- View
- Output
- Conclusion
1. Route
Open application/config/route.php
file.
Edit –
$route['404_override'] = 'Custom404';
Here, Custom404
is the name of the controller.
2. Controller
Create a new Custom404.php
file in application/controllers/
directory.
In index()
method execute $this->output->set_status_header('404');
and load error404
view.
Completed Code
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Custom404 extends CI_Controller { public function __construct() { parent::__construct(); // load base_url $this->load->helper('url'); } public function index(){ $this->output->set_status_header('404'); $this->load->view('error404'); } }
3. View
Create a error404.php
file in application/views/
directory.
Here, I created a simple 404 error page.
Completed Code
<!doctype html> <html> <head> <title>404 Page Not Found</title> <style> body{ width: 99%; height: 100%; background-color: mediumturquoise; color: white; font-family: sans-serif; } div { position: absolute; width: 400px; height: 300px; z-index: 15; top: 45%; left: 50%; margin: -100px 0 0 -200px; text-align: center; } h1,h2{ text-align: center; } h1{ font-size: 60px; margin-bottom: 10px; border-bottom: 1px solid white; padding-bottom: 10px; } h2{ margin-bottom: 40px; } a{ margin-top:10px; text-decoration: none; padding: 10px 25px; background-color: ghostwhite; color: black; margin-top: 20px; } </style> </head> <body> <div> <h1>404</h1> <h2>Page not found</h2> <a href='<?= base_url(); ?>' >Back to Homepage</a> </div> </body> </html>
4. Output
404 Error page looks like this.
5. Conclusion
You need to create a controller from where load custom 404 view page. Assign Controller name to $route['404_override']
in route.php
.
If you found this tutorial helpful then don’t forget to share.
Introduction
CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it has an error logging class that permits error and debugging messages to be saved as text files.
show_error()
This function will display the error message supplied to it using the following error template:
Path — application/errors/error_general.php
The optional parameter $status_code determines what HTTP status code should be sent with the error.
Syntax
show_error($message, $status_code, $heading = 'An Error Was Encountered')
Parameters:
$message (mixed)
– Error message$status_code (int)
– HTTP Response status code$heading (string)
– Error page heading
Return type: void
Source
show_error
in codeigniter.com
show_404()
This function will display the 404 error message supplied to it using the following error template:
Path — application/errors/error_404.php
The function expects the string passed to it to be the file path to the page that isn’t found. Note that CodeIgniter automatically shows 404 messages if controllers are not found.
CodeIgniter automatically logs any show_404()
calls. Setting the optional second parameter to FALSE will skip logging.
Syntax
show_404($page = '', $log_error = TRUE)
Parameters:
- $page (string) – URI string
- $log_error (bool) – Whether to log the error
Return type: void
Source
show_404
in codeigniter.com
log_message()
This function lets you write messages to your log files. You must supply one of three «levels» in the first parameter, indicating what type of message it is (debug, error, info), with the message itself in the second parameter.
Example:
if ($some_var == "") {
log_message('error', 'Some variable did not contain a value.');
}
else {
log_message('debug', 'Some variable was correctly set');
}
log_message('info', 'The purpose of some variable is to provide some value.');
Syntax
log_message($level, $message);
Parameters:
$level (string)
– Log level: ‘error’, ‘debug’ or ‘info’$message (string)
– Message to log
Return type: void
There are three message types:
- Error Messages. These are actual errors, such as PHP errors or user errors.
- Debug Messages. These are messages that assist in debugging. For example, if a class has been initialized, you could log this as debugging info.
- Informational Messages. These are the lowest priority messages, simply giving information regarding some process. CodeIgniter doesn’t natively generate any info messages but you may want to in your application.
Note: In order for the log file to actually be written, the «logs»
the folder must be writable. In addition, you must set the «threshold» for
logging inapplication/config/config.php
. You might, for example, only want error messages to be logged, and not the other two types. If you set it to zero logging will be disabled.
Improve Article
Save Article
Improve Article
Save Article
We often see the 404 error page while using websites. This error page will encounter only when we navigate to a broken link. In CodeIgniter, it is possible to create a custom 404 page to change the look of the 404 page. So in this article, we will look into how to create the custom 404 error page.
In order to create a custom 404 error page, we need to do three steps:
- View
- Controller
- Route
View: In the View section, we create an error404.php page in the application/views/directory which will be displayed when any problem occurs while navigating between URLs. The standard error page doesn’t contain any CSS. In order to add styles and make the 404 Error page more attractive, a custom page can be created. Below is the HTML code that also consists of Internal CSS.
error404.php
< !doctype html>
<html>
<head>
<title>Page Not Found 404 Error</title>
<style>
body {
background - color: green;
color: white;
}
div {
position: absolute;
text-align: center;
width: 400px;
height: 300px;
top: 45%;
left: 50%;
margin: -100px 0 0 -200px;
}
h1,
h2 {
text - align: center;
}
h1 {
font - size: 50px;
margin-bottom: 10px;
border-bottom: 1px solid white;
}
</style>
</head>
<body>
<div>
<h1>404</h1>
<h2>Page not found</h2>
</div>
</body>
</html>
Controller: In Controller phase, we create a customError404.php in application/controllers/directory. Inside the ccustomError404.php code, in index() method load error404 view and also execute $this->output->set_status_header(‘404’). Let’s look at the code of controller.
customError404.php
<? php
defined(
'BASEPATH'
) OR
exit
(
'No direct script access allowed'
);
class
CustomError404
extends
CI_Controller {
public
function
__construct() {
parent:: __construct();
$this
-> load -> helper(
'url'
);
}
public
function
index() {
$this
-> output -> set_status_header(
'404'
);
$this
-> load -> view(
'error404'
);
}
}
Route: In this step, we need to edit the route.php file which is present in the application/config/ directory and assign the custom controller customError404.php to $route[‘404_override’].
Steps:
- Open application/config/route.php
- Edit it to $route[‘404_override’]=’customError404.php’;
Output: The custom 404 Error page we created in this article is look like:
404 Error Page
Reading Time: 4 minutes
6,560 Views
When routes not exists what we are looking for in web application, then we can handle this via 404 error page i.e page not found. Inside this article we will discuss such type of concept in CodeIgniter 4.
We will create a custom 404 page in CodeIgniter 4. We will override the default 404 page of CodeIgniter 4 application.
Learn More –
- Create Custom Spark Console Command in CodeIgniter 4
- Create Fake REST APIs Server in CodeIgniter 4
- Create Signature Pad & Save Using jQuery in CodeIgniter 4
- CRUD Operation in CodeIgniter 4 Tutorial
Let’s get started.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
$ composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Environment (.env) Setup
When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Either we can do via renaming file as simple as that. Also we can do by terminal command.
Open project in terminal
$ cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
Enable Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.
Open .env file from root.
# CI_ENVIRONMENT = production
// Do it to
CI_ENVIRONMENT = development
Now application is in development mode.
Application 404 Route Settings
Open Routes.php from /app/Config folder.
Inside this file search for set404Override().
$routes->set404Override();
When we open any routes which is not configured in application, then getting 404 error page. By default this is 404 error page template of CodeIgniter 4.
This default layout is loaded from /app/Views/errors/html/error_404.php
We need to change this layout.
404 Custom Layout Setup
To create a custom layout for 404 error page, we need to use the same block of code what we have seen above. We need to add a callback function into it to return template view file.
Use a Static Message
Example
Let’s set a static message for getting 404 error in application.
$routes->set404Override(function() {
echo "<h3>Page not found - Custom Message</h3>";
});
Whenever we get any 404 then this static message will be rendered. No default layout will be used.
Use a View Template File
Let’s create a view file 404.php inside /app/Views.
Open 404.php and write this piece of code into it.
<!doctype html> <html> <head> <title>404 Page Not Found</title> <style> body { width: 99%; height: 100%; background-color: #d1486894; color: #fff; font-family: sans-serif; } div { position: absolute; width: 400px; height: 300px; z-index: 15; top: 45%; left: 50%; margin: -100px 0 0 -200px; text-align: center; } h1, h2 { text-align: center; } h1 { font-size: 60px; margin-bottom: 10px; border-bottom: 1px solid white; padding-bottom: 10px; } h2 { margin-bottom: 40px; } a { margin-top: 10px; text-decoration: none; padding: 10px 25px; background-color: #fff; color: black; margin-top: 20px; border-radius: 10px; } </style> </head> <body> <div> <h1>404</h1> <h2>Page not found</h2> <a href='<?= base_url() ?>'>Back to Site</a> </div> </body> </html>
Setting template to 404 override method
$routes->set404Override(function() {
return view("404");
});
Now, when we open any application route which don’t really exists then we will get custom 404 page what we created.
We hope this article helped you to learn Create Custom 404 Page in CodeIgniter 4 | Page Not Found in a very detailed way.
Buy Me a Coffee
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.