Where should assets go in a CodeIgniter project?


Question

I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?

1
18
3/23/2019 10:22:35 AM

Accepted Answer

I usually put separate folders at the root level, so I end up with a directory structure like this:

/system
/css
/js
/img

Seems to work for me - when you use site_url(url), the URL it generates is from the root, so you can use site_url('css/file.css') to generate URLs to your stylesheets etc.

15
10/7/2008 1:51:25 PM

Personally, I rip the application directory out of the system directory and make it a sibling to system. I then create a project directory in public_html (www) where I move index.php and store my public assets.

Let's assume the project you're working on is called projekt. In the parent directory to public_html (www) create a directory called CISYSTEM, and inside that directory create a directory from the version you're using, 202, 210 etc.

/CISYSTEM
    /202
    /210
    /another_CI_version
/projekt_application
    /models
    /views
    /controllers
    /private_assets
/public_html
    /projekt
        index.php
        .htaccess
        css
        img
        js
        lib

The beauty of this directory structure is it adds another layer of security and makes it dead-easy to upgrade/swap out your CI core. Plus, you're not supposed to make changes to the core - having a single directory where your core is stored and having all projects reference it keeps things DRY.

All this directory shuffling requires you to reroute a few things though. Luckily, CodeIgniter makes it easy -- all changes can be made in the index.php file.

Open index.php and reroute a couple things:

Change: $system_path = 'system';

To: $system_path = '../../CISYSTEM/210';

Change: $application_folder = 'application';

To: $application_folder = '../../projekt_application';


Also, I see a lot of people talking about using site_url() in the other answers. I recommend a less verbose way of using site_url()... you don't have to call it every time if you make use of HTML's <base> element:

<base href="<?= site_url();?>">

Just include that in your application's <head> and you can call your controllers directly... as in:

<a href='controllername/functionname'>Some Action</a>

Cheers


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon