How to Use CSS,JS and Images in CodeIgniter

CodeIgniter is based on MVC Pattern in which Our project is divide into three folders Model, View, and Controller. In the Model folder, we keep our database-related files, and In View, we keep our HTML files. In Controller, we keep our PHP logic files. We have separated our project into different folders, but beginners don’t know where to keep our images, CSS, and js files.

Loading CSS, images, and js files in CodeIgniter are not easy compared to core PHP. Here are some steps following to load CSS, js, and image :

Step1:  Create a media folder in the root folder where your application folder and index.php file exist.

Step2: Create a CSS folder, js folder, and images folder in the media folder to keep your images, CSS, and js files.

Step3: Now, you have to load URL helper to use the base_url() function of CodeIgniter. Go to your application>config>autoload.php file and find the following code:

$autoload['helper'] = array();
Here add the url helper in this array like this
$autoload['helper'] = array('url');


Step4:
Check your application>config>config.php file you have written base_url() or not. If not, then write your project base_url like this:

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

Here immaterial is your folder name.


Step5:
Now open your file

<link rel="stylesheet" href=”css/style.css">
Replace this link with this code
<link rel="stylesheet" href="<?php echo base_url();?>media/css/style.css">

Here base_url() is your project's main URL, and media and CSS is the folder name. Replace all the CSS files like this way add base_url and media folder.


Step6:
To load the js file and image, do the following:

JS Code: 
<script src="js/main.js"></script>
Replace this with this code
<script src="<?php echo base_url();?>media /js/main.js"></script>

Replace all the js files like this way add base_url and media folder.

Images:
  <img src="<?php echo base_url();?>media/images/abc.jpg" alt="logo" class="img-fluid">

Replace all the images like this add base_url and media folder.

 

Categories: web development codeigniter

Trending Courses

CodeIgniter

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Advance Digital Marketing

Regular : 6 Months

Fastrack : 3 Months

Crash : 2 Months

React JS

Regular : 45 Days

Fastrack : 25 Days

Crash : 15 Days

Laravel

Regular : 45 Days

Fastrack : 20 Days

Crash : 10 Days

Front End Developer

Regular : 6 Months

Fastrack : 4 Months

Crash : 2 Months

Related Blogs

Request For Demo