0

I am working on hook file, i am using pre_controller function of hook, but when i tried to use base_url() function in it, it is not working for me, it give me this error Call to undefined function base_url(), can anyone please help me to resolve this error ? here i have added my whole function

$hook['pre_controller'] = function()
{
    $this->CI = get_instance();
    $ci =& get_instance();
    $router =& load_class('Router', 'core','uri','url');
    $controller_name = $router->fetch_class();  
    $action_name = $router->fetch_method();  
    $segement = $router->uri->segment(2);
    echo base_url(); die;
    try {   
        $rc = new ReflectionClass($controller_name);
    } catch (Exception $ex) {
        if($segement == "") {
            echo base_url(); die;
            //header("Location:".$controller_name.'/overview');
            //redirect($controller_name.'/overview');
            //exit;
        }
    }  
};
Nikul Panchal
  • 663
  • 1
  • 14
  • 32

2 Answers2

1

This won't work because base_url() gets initialized if a Controller is loaded. And pre_controller basically means the opposite.

There are two options for you

Option 1

create a PreControllerHook.php in your application/hooks/ directory.

class PreControllerHook extends CI_Controller
{
    public function initialize()
    {
        $controller_name = $this->router->fetch_class();  
        //... and so on
    }
}

Setup your hooks.php config

$hook['pre_controller'] = [
    [
        'class' => 'PreControllerHook',
        'function' => 'initialize',
        'filename' => 'PreControllerHook.php',
        'filepath' => 'hooks'
    [
];

Option 2

create a PostControllerConstructorHook.php in your application/hooks/ directory.

class PostControllerConstructorHook
{
    public function initialize()
    {
        $ci = get_instance();
        $controller_name = $ci->router->fetch_class();  
        //... and so on
    }
}

Setup your hooks.php config

$hook['post_controller_constructor'] = [
    [
        'class' => 'PostControllerConstructorHook',
        'function' => 'initialize',
        'filename' => 'PostControllerConstructorHook.php',
        'filepath' => 'hooks'
    [
];

You can find more information on their official documentation page here.

Atural
  • 5,389
  • 5
  • 18
  • 35
0

i hope this will work for you

base_url() function not working in codeigniter

madara uchiha
  • 202
  • 2
  • 9