Search code examples
phpcodeigniterrelative-pathbase-url

Why you should use base_url() in relative links (Codeigniter etc.)


Why in relative links I should always use syntax base_url+link in CodeIgniter? For example:

<a href="<?php echo base_url()?>link22.php">

instead of

<a href="/link22.php'>

when I've got declared <base href="<?php echo base_url()?>"> in HTML head? What are the benefits?


Solution

  • Good question.

    Short words (used in below)

    CI - Codeigniter


    Why you should use base_url()??

    base_url() is a the function which determine your project destination which act as $_SERVER['REQUEST_URI'] in php. This will know where your actual project contains.


    Where we can modify/define base_url()??

    Path - application/config/
    File name - config.php
    

    Can We just use base_url() function?

    No. You can't. In CI they having some libraries and helper which help us to use CI more friendly. So to base_url() there is an helper file call url.

    How to load it??

    Path - application/config/
    File name - autoload.php
    

    there is function like this $autoload['helper'] = array();. So add the helper to that

    $autoload['helper'] = array('url');
    

    Is there any method to modify/define base_url()??

    Yes. There are two methods you can define base_url()

    Method 01

    $config['base_url'] = '';
    

    Method 02

    $config['base_url'] = 'http://localhost/foldername/';
    

    Difference between Method 01(M1) and Method 02(M2)

    M1 - When we keep empty base_url it will automatically determine your project scope. So when ever you can't find path or having some doubt this is recommend.
    M2 - There is no difference between M1, In here you know path. So can define it.

    Which method is good/recommended?

    As my suggestion is Method 01 is the best.


    Why we use echo base_url() instead of just base_url()

    base_url() is an variable which pre+defined(Codeigniter+User) in CI framework, which we can use entire project. So to show content of variable in php, we use echo. In here also same theory comes to this.


    Why this <a href="/link22.php'> will not work

    Codeigniter Framework build with MVC Structure. (MVC stand for Model View Controller.)

    So when open your project it will call to Controller, then if there any incoming values from Database. It will get that from the Model, Then it will load relevant view which mentioned in Controller.

    If this link22.php is some related file to your project you have to place that inside View folder.


    Can I include php file to another view

    Yes. you can. For that you have to use APPPATH.

    Example - Assume link22.php is inside view/links/ So you have to use

    APPPATH.'view/links/link22.php'
    

    Some Usefull links

    1. URL Helper