Last updated on November 18, 2022
In this post, I will show you how easy it is to set up maintenance mode in CodeIgniter using CI’s hooks. while updating your web application it’s always better to show meaningful maintenance messages to the end users, instead of showing errors.
We gonna use CIs hooks to set up the maintenance page. Using hooks you can extend the Framework Core. CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.
Let’s create a file called maintenance_view.php
in application/views
directory with the below content:
<h1 class="text-center">Site Under Maintenance</h1>
<div class="container">
<p class="text-center">Sorry for the inconvenience. To improve our services, we have momentarily shutdown our site.</p>
</div>
To use hooks, you need to enable hooks, so edit the application/config/config.php
file and set $config[‘enable_hooks’] to TRUE.
$config['enable_hooks'] = TRUE;
To make it simple to enable and disable the maintenance mode, let’s define a new config variable for maintenance mode. So add the following config code to the application/config/config.php
file.
$config['maintenance_mode'] = TRUE;
To let the system know about the maintenance hook, edit the application/config/hooks.php
file and register the maintenance hook.
$hook['pre_system'][] = array(
'class' => 'maintenance_hook',
'function' => 'offline_check',
'filename' => 'maintenance_hook.php',
'filepath' => 'hooks'
);
In the above config array,pre_system:
One of the available hook points in CI. The hook will be called very early during system execution and which is a good point to show the maintenance page.
class: The name of the class wishes to invoke.
function: The method name wishes to call.
filename: The filename contains the class/function.
filepath: The name of the directory containing the hook script.
Maintenance Hook Class
Let’s create a new hook file called application/hooks/maintenance_hook.php
and add the following PHP code. The following code checks the config value of the maintenance variable which we have defined in the application/hooks/config.php file and if that value is true, it will load the site maintenance page from the application views folder.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Check whether the site is offline or not.
*
*/
class Maintenance_hook
{
public function __construct(){
log_message('debug','Accessing maintenance hook!');
}
public function offline_check(){
if(file_exists(APPPATH.'config/config.php')){
include(APPPATH.'config/config.php');
if(isset($config['maintenance_mode']) && $config['maintenance_mode'] === TRUE){
include(APPPATH.'views/maintenance_view.php');
exit;
}
}
}
}
Enable/Disable Maintenance Mode
Now you can enable the maintenance mode by settings $config['maintenance_mode'] = TRUE;
and to disable the maintenance mode, change it to $config['maintenance_mode'] = FALSE;
.