Workaround for url/u not working in config.php


#1

When on a localhost installation like http://localhost/my-domain.com and try to do echo url() in config.php, it will output http://localhost instead of http://localhost/my-domain.com.

I run into this from time to time and I’ve made a quick and dirty solution for it. Feel free to improve it if you want.

config.php

The functions below both needs to be in config.php because the plugins has not yet been loaded.

function is_localhost() {
    $whitelist = array( '127.0.0.1', '::1' );
    return in_array( $_SERVER['REMOTE_ADDR'], $whitelist);
}

function getUrl($path = '/') {
    if(is_localhost()) {
        $dir = pathinfo($_SERVER['SCRIPT_NAME'])['dirname'];
        return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . $dir . '/' . $path;
    } else {
        return u($path);
    }
}

// echo url() will not work on localhost/my-domain.com
echo getUrl('assets/css/style.min.css');

c::set('my-absolute-config', getUrl('assets/css/style.min.css'));

#2

What is your use case for calling the url method in the config?

I don’t think this workaround is necessary. You might as well set your option like this:

c::set('my-absolute-config', 'assets/css/style.min.css');

Then call the url method in your plugin (or wherever)

<?= url(c::get('my-absolute-config', 'some_default')); ?>