Search code examples
codeigniterphp-7base-urlcodeigniter-4

Setting Dynamic base URL in CodeIgniter 4.0.2


I am migrating my project from CodeIgniter 3 to CodeIgniter 4. I am getting confused for the new structure of the framework. So here's my problem,

I am setting my base url in App.php to:

protected $proj_root= "http://".$_SERVER['HTTP_HOST'];
protected $proj_root2  = str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
protected $mybase= $proj_root.$proj_root2;
public $baseURL =  $mybase;

But I am getting error like this:

Fatal error: Constant expression contains invalid operations in D:\xampp\htdocs\delivery_dashboard\app\Config\App.php on line 26

So literally I can only do this:

public $baseURL = "http://localhost/my_project/"

How can I set my base url dynamically using $_SERVER['HTTP_HOST'] or is there any workaround here?

Thanks for the help!


Solution

  • I dont know the exact solution but i shared my way of solution to you Go to app/Config/Constants.php

        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https://'.$_SERVER['HTTP_HOST'] : 'http://'.$_SERVER['HTTP_HOST'];
        defined('BASE') || define('BASE',$protocol);
    

    In app/Config/App.php

     public $baseURL    = BASE;
    

    Hope this Helps