问题
I am working on a small project and all of my urls are written without base_url()
function. So I was thinking what does those base_url()
functions help with my urls. I know it will prefix the url based on configs file preferences. But simply I wanna ask
What is the advantage of using them ? and whats the disadvantage of not using them ?
回答1:
The main advantage is that; when you want to migrate your project to online or in a different server; you won't need to edit your hard-coded links. The base_url() will make your inside links to get their base url dynamically.
echo base_url("blog/post/123");
will return
http://example.com/blog/post/123
in example.com
and will return
http://jms.com/blog/post/123
in jms.com
回答2:
base_url
is needed when you create login/signup with email verification or forgot password functionality (Verifying by clicking the links like this http://yourdomain.com/auth/userid/code).
This is only one example, may have lot of uses.
回答3:
the difference of base_url()
and site_url()
is that
both returns the url of your site but site_url()
returns your site url, with attached index.php
or on what you have configured $config['index_page'] = ''
in application/config/config.php
example www.yoursite.com/chicken/turkey
when using base_url()
: Returns your site base URL, as specified in your config file.
you will get wwww.yoursite.com
when using site_url()
:
you will get www.yoursite.com/index.php
site_url()
is usefull if you haven't change your .htaccess
and you still access your controllers with index.php
base_url()
is usefull when linking your css,js,or media stuffs. Granting that you still use index.php
when accessing your controller/method
回答4:
Its needed every-where, or at least we should use everywhere. Do you know, absolute url is far better then relative url? So, when you are using an absolute urls for all links on your site, instead of hard coded root domain name, you can use the "base_url()" function. Moreover, CI reactor is smart enough to detect the original base url, so you even don't need to enter it in config file.
回答5:
I usually using the base_url() for the correct paths to the static files (css, js, img) files and the site_url() for the links to pages. site_url() will return with url_suffix
witch could be set in application/config/config.php file
回答6:
Advantage:-if you not use base_url() and you want to switch directory/server of your site , you should change the path all over the project.
if you use base_url(), just change it at onece in config.php ,effect on all site.
来源:https://stackoverflow.com/questions/14764975/when-do-we-need-to-use-base-url-function-in-codeigniter