Change/set a dynamic base URL in CodeIgniter 4: is very easy and reliable. Especially, in Codeigniter 4 version. If we didn’t configure base_url() or site_url() then CodeIgniter find it automatically but its not perfect solution. sometimes, the automatic base URL creates a problem for developers. You can also Set/Change Codeigniter 4 Environment Variable to Development or Production
When $config['base_url'] is not set, CodeIgniter 4 tries to automatically detect what your website’s base URL is. This is done purely for convenience when you are starting the development of a new application.
Auto-detection of the base URL is never reliable and also has security implications, which is why you should always have it manually configured in CodeIgniter 4.
Read Codeigniter 4 Full Tutorial Guide OR Download Codeigniter 4
Why do we need to set a dynamic base URL in CodeIgniter 4?
Basically, In most cases, we need to shift our CodeIgniter application from a Local Server to a Live Server and vice-versa. So, every time we have to change the base URL from the config.php file. It takes a little bit more time and also increases 1 more step every time. A good developer already has solutions to save time.
So here, I have a solution for you. you can try this code on \application\config\config.php:
Step1: Get HTTP or HTTPS from URL
$config
[
'base_url'
] = ((isset(
$_SERVER
[
'HTTPS'
]) &&
$_SERVER
[
'HTTPS'
] ==
"on"
) ?
"https"
:
"http"
);
this line of code will help you to detect the HTTP or HTTPS. this is also a major issue in many cases. because when you SSL certificated expired or user tries request with HTTP then fixed URL return error or creates a bug.
Step2: Get Host or domain name from URL
$config
[
'base_url'
] .=
"://"
.
$_SERVER
[
'HTTP_HOST'
];
Step3: get Script Name from URL
$config
[
'base_url'
] .=
str_replace
(
basename
(
$_SERVER
[
'SCRIPT_NAME'
]),
""
,
$_SERVER
[
'SCRIPT_NAME'
]);
So, here I concatenated or combined 3 lines in $config[‘base_url’] to set Dynamic base URL in CodeIgniter 4. I think this is the easiest and the best solution for CodeIgniter 4 dynamic base URL or Site URL.
$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']);
Also read, How to get a Controller and Method Name in Codeigniter 4
The post How to set a Dynamic Base URL in CodeIgniter 4 – Change base_url() appeared first on Learn PHP online.
This post first appeared on Learn PHP Online - Best Free PHP Tutorial For Beginners To Advanced 2019, please read the originial post: here