Search code examples
phpcodeigniter-4base-url

How to set Dynamic $baseURL on app->config->app.php using codeigniter 4


I got the error on IDE "Syntax error unexpected variable $_SERVER" and app "Parse error: syntax error, unexpected '$http_https' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST) in C:\laragon\www\laplacegroup\app\Config\App.php on line 30"

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

protected $host = $_SERVER['HTTP_HOST'];
$http_https = isset($_SERVER['HTTPS']) ? "https://" : "http://";
public $baseURL = $http_https . $host;

How can fix it


Solution

  • Solution I use is to dynamically define a variable in app/Config/Constants.php and use it in app/Config/App.php.

    App.php :

    public $baseURL = BASE_URL;
    

    Constants.php :

    $host = $_SERVER['HTTP_HOST'];
    $http_https = isset($_SERVER['HTTPS']) ? "https://" : "http://";
    $baseURL = $http_https . $host;
    define('BASE_URL', $baseURL);
    

    It works but seems like a bit hacky in my opinion. I never tried to find out if a better solution exists though.