0

All these days I thought that CodeIgniter did not allow direct access to file(s) in the application (I mean the application itself and not the application folder).

So, if I have the following structure under the folder, www:

ROOT
|____APPLICATION
        |___________JS/mine.js
        |___________VIEWS/my_view.php

And if I want to include mine.js in my_view.php, I would need to refer the JS file using the base_url() function as follows:

<script type="text/javascript" src="<?php echo base_url();?>js/mine.js"></script>

Looks like I was wrong, I can refer to it relatively as well. Like:

<script type="text/javascript" src="../js/mine.js"></script>

Any thoughts/opinions?

Which one is a good practice? And why?

1
  • seems like you deleted/modified the htaccess file.... anyways relative url won't work in all cases none the less. Commented May 6, 2013 at 17:04

2 Answers 2

8

It's always a smart idea to use base_url() so if your URL changes, all your links don't break.

base_url() is going to return the full TLD, plus any folders your site is in.

Best practice is to keep your assets out of the application, or any other system folders. Most CodeIgniter sites will structure their assets as follows:

ROOT
|____APPLICATION
|____ASSETS
|      |________ CSS
|      |________ JS
|      |________ IMG
|____SYSTEM

And then referenced like so:

<script type="text/javascript" src="<?php echo base_url('assets/js/mine.js')"></script>
Sign up to request clarification or add additional context in comments.

2 Comments

yes, and even better (if you could do that on your hosting) put appliciation and system folder outside of ROOT(www or public_html folder) so when something went wrong with server or your website is hacked only your assets would be accessible by the intruder.
I've seen so many crazy explanations of how to link to assets in CI, but this is by far the most straightforward way, using an existing CI method. Thank you.
4

It is always a good idea while using MVC to keep all assets folders (css, js and images) in root directory rather than keeping inside application or any other folder and accessing them using base_url.

<script type="text/javascript" src="<?php echo base_url();?>js/mine.js"></script>

So I think above line you mentioned is the proper way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.