CodeIgniter and External Resources

Jim O'Halloran • September 21, 2007

php codeigniter

There's been a couple of posts on the CI forums recently about either controllers running twice or external resources (such as images, css, or javscript) not loading. Whenever I've run into this problem it's always come down to issues around the references to the externals. Usually, usage of a relative link rather than an absolute one.

Incorrect referencing causes duplicate controller runs because the browser would load the page, then start pulling down the images, etc and run the application code again. Lets work through an example and see why this happens. If we have the following image tag:

<img src="images/spacer.gif" />

This will try to load http://www.example.com/images/spacer.gif if it's used on the home page (i.e. http://www.example.com/). Problems begin when we start using the URL to access CI controllers and methods. For example our relative link becomes http://www.example.com/index.php/controller/method/images/spacer.gif when the current page is http://www.example.com/index.php/controler/method/. The browser will attempt to load our image from the incorrect location, resulting in the controller being executed a second time (CI intercepts and handles the request for index.php/controller/method). It won't result in an infinite loop because the browser will treat the html returned from the second execution as bad image data and discard it. Note: If you use .htaccess to remove the index.php from the URL the same thing still occurs.

The best fix for that problem is to load all external files with a bit of assistance from the URL helper, like so:

<img src="<?php echo(base_url()); ?>images/spacer.gif" />

That will ensure that images are always loaded from an absolute location. When I implemented this on all of my javascript, css, etc my problem went away. Watch also for javascript code which loads resources from a relative path, as this will also be upset by CI's "fake" directory structure.