You should use hook pre_controller
BUT there is one problem: CodeIgniter does not allow to use DB class in pre_system
and pre_controller
hooks, so you can not install session table using active record ( $this->db->query()
).
I know that CodeIgniter guide says
pre_controller -
Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.
but this is NOT true... (you can read about it on other posts: pre_controller hook does not load base classes like docs state?).
Anyway, you can connect to your database manually. This is a little dirty solution, but I don't know better one.
Here is my code to install session table automatically.
<?php
class SessionTableInstaller
{
public function install()
{
if( $db_config = $this->getDBConfig() ) {
$db_handle = mysql_connect($db_config['hostname'], $db_config['username'], $db_config['password']);
if ($db_handle === FALSE) {
throw new Exception('Cannot connect with MySql server');
}
if (mysql_select_db($db_config['database'], $db_handle) === FALSE) {
throw new Exception('Cannot select database');
}
$query = "CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id) ,
KEY `last_activity_idx` (`last_activity`)
) ENGINE=InnoDB default CHARSET=utf8 ;";
mysql_query($query);
mysql_close($db_handle);
}
}
private function getDBConfig()
{
require __DIR__ . '/../config/database.php';
if(!isset($db) || !isset($active_group)) {
return false;
}
$db_config = $db[ $active_group ];
return $db_config;
}
}
/* End of file sessionTable.php */
/* Location: ./application/hooks/sessionTable.php */
And here is code in config/hooks.php
$hook['pre_controller'] = array(
'class' => 'SessionTableInstaller',
'function' => 'install',
'filename' => 'sessionTable.php',
'filepath' => 'hooks'
);