I've got a CI instance which connects to a Db and checks permissions before serving pages. If the page isn't accessible to the current user, it redirects to a login page.
The login page, obviously, has permissions set so that it's accessible to all users.
After a recent glitch, the database server came back up on a different IP address (thank you Amazon, EC2). This resulted in CI being unable to check permissions for any page - including Login. Since the code assumes anything other than a Yes is a No, it redirected to Login. The result was an infinite redirect loop.
While this exact problem shouldn't happen again (Static elastic IP), I'd like to detect when the Db connection is down and handle it appropriately.
I've seen This SO Question which is what I'm trying to achieve but I'm not explicitly loading the database in any controllers, it's in the autoload config file.
So,
How can I query the state of the Db connection from inside CI? Do I have to run a useless query and check if I get results back or is there a more elegant solution?
Edit: The check is currently being performed in a hook:
$hook['post_controller_constructor'] = array(
'class' => 'AuthHook',
'function' => 'ValidateCredentials',
'filename' => 'auth.php',
'filepath' => 'hooks'
);
ini_set('display_errors', 'Off'); // Load the database config file. Why not just use $this->load->database(), which does everything you are doing manually and more? Using $this->load->database(); will throw a error page if the connection failed or for example the config file does not exists.
CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at application/config/database. php. You can also set database connection values for specific environments by placing database.
You can extend the controller and load the database in its constructor:
class My_Controller extends CI_Controller {
public function __construct(){
parent::__construct();
if ( $this->load->database() === FALSE )
{
//do something
}
}
}
All your controllers will inherit the new controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With