How to include image, css and js file in codeigniter?

Last updated 1 year, 10 months ago | 2074 views 75     5

Tags:- CodeIgniter

Codeigniter | Include image, CSS, and js file

In Codeigniter, we need to load URL helper in the controller and then use the base_url() function to load the resources.

// loading script
<script type='text/javascript' src="<?php echo base_url('js/jquery.min.js'); ?>"></script>

// loading image
<img src="<?php echo site_url('images/myimage.jpg'); ?>" />

Codeigniter uses an absolute path to load the resources. Also, there is an inbuild helper class that is used to load the resources in view.
so for this let's create an assets folder in our root directory. Again create a CSS, js, and image folder inside the assets folder and placed the CSS file in css folder, the js file in the js folder, and the image file in the image folder. 

For now let's say we have a "style.css" file in css folder, "img.jpg" in the image folder, and "demo.js" in the js folder.

The directory structure seems like bellow:

 // root folder
            |          |___css|
            |          |      |___style.css
            |          |
            |          |___images|
            |          |         |___img.jpg
            |          |___js|
            |                |___demo.js

Now create a "Demo.php" file with the below code and save it inside the application/controllers folder. 


   class Demo extends CI_Controller {
      public function index() { 




Create a view file called demo.php and pest the bellow code and save it inside the application/views folder.

<!DOCTYPE html> 
<html lang = "en">
      <meta charset = "utf-8"> 
      <title>Codeigniter | Include image, css and js file</title> 
      <link rel = "stylesheet" type = "text/css" href = "<?php echo base_url('assets/css/style.css'); ?>"> 
      <script type = 'text/javascript' src = "<?php echo base_url('assets/js/demo.js'); ?>"></script> 
      <img src="<?php echo base_url('assets/images/img.jpg') ?>">
      <a href = 'javascript:test()'>Click Here</a> to execute the javascript function. 


Code for "style.css" file

body { 
    background: #000;
    color: #FFF;
    font-size: 24px;
    text-align: center; 


Code for "demo.js" file

function test() { 
   alert('This page contain one image'); 


Now use the following URL in the browser to execute the above example.