Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 368
Roshan Avatar asked Oct 27 '25 06:10

Roshan


1 Answers

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

like image 91
Boominathan Elango Avatar answered Oct 28 '25 21:10

Boominathan Elango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!