📜 ⬆️ ⬇️

Flexible base_url

Somehow I wanted that when accessing the page via https, all internal links were also changed to versions with https. Since the page view is loaded with different urls, relative paths did not pass ( js / script.js ) and I decided to use the base_url function ( echo base_url (). 'Js / script.js' ), but the fact is that it substitutes the contents of the variable $ config ['base_url'] , which in turn is static.
After a bit of searching, I found a solution - a dynamic base path in $ config ['base_url']. Also a positive effect is that now you do not need to change the base_url when transferring files between domains.

The most convenient way is to add these changes immediately to the system / config / config.php file.

$config[ 'base_url' ] = ((isset($_SERVER[ 'HTTPS' ]) && $_SERVER[ 'HTTPS' ] == "on" ) ? "https" : "http" );
$config[ 'base_url' ] .= "://" .$_SERVER[ 'HTTP_HOST' ];
$config[ 'base_url' ] .= str_replace(basename($_SERVER[ 'SCRIPT_NAME' ]), "" ,$_SERVER[ 'SCRIPT_NAME' ]);


There is a more difficult option:
/* Detect ssl connectivity */
if ( isset($_SERVER[ 'HTTPS' ]) ) {
$ssl = $_SERVER[ 'HTTPS' ];
}elseif ( isset($_SERVER[ 'HTTP_FRONT_END_HTTPS' ]) ) {
$ssl = $_SERVER[ 'HTTP_FRONT_END_HTTPS' ];
} else {
$ssl = "OFF" ;
}
$root = (stripos($ssl, "ON" ) !== FALSE) ? "https" : "http" ;

/* Many pages/apps served through the same domain */
if ( isset($_SERVER[ 'HTTP_X_FORWARDED_HOST' ]) ) {
list($host) = explode( ',' , str_replace( ' ' , '' , $_SERVER[ 'HTTP_X_FORWARDED_HOST' ]));
} else {
$host = $_SERVER[ 'HTTP_HOST' ];
}

$root .= "://" .$host;

if ( ! isset($_SERVER[ 'ORIG_SCRIPT_NAME' ]) ) {
$root .= str_replace(basename($_SERVER[ 'SCRIPT_NAME' ]), "" ,$_SERVER[ 'SCRIPT_NAME' ]);
}
else {
$root .= str_replace(basename($_SERVER[ 'ORIG_SCRIPT_NAME' ]), "" ,$_SERVER[ 'ORIG_SCRIPT_NAME' ]);
}

$config[ 'base_url' ] = "$root" ;


Code taken from the Codeigniter forum: Automatic configbase url

')

Source: https://habr.com/ru/post/58237/


All Articles