How to Create and Load View in CodeIgniter

In CodeIgniter, creating and loading views is a fundamental part of building web applications. Views are used to render the HTML content that is presented to the user. Here's a step-by-step guide on how to create and load views in CodeIgniter:

Step 1: Create a View File

Inside the application/views directory of your CodeIgniter project, create a new PHP file for your view. For example, let's create a view file named welcome_message.php.

<!-- application/views/welcome_message.php -->

<!DOCTYPE html>
    <title>Welcome to CodeIgniter</title>
    <h1>Welcome to CodeIgniter!</h1>
    <p>This is a simple view rendered by CodeIgniter.</p>

Step 2: Create a Controller

Inside the application/controllers directory, create a new PHP file for your controller. For example, let's create a controller named Welcome.php.

<!-- application/controllers/Welcome.php -->

defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
        // Load the view file 'welcome_message'

In this example, we have created a controller named Welcome with an index method. Inside the index method, we load the welcome_message view using the $this->load->view() method.

Step 3: Configure Routes (Optional)

By default, the CodeIgniter framework will route to the Welcome controller's index method when you access the base URL of your application (e.g., http://localhost/codeigniter). However, if you want to set a custom route, you can configure it in the application/config/routes.php file.

// application/config/routes.php

$route['custom-route'] = 'welcome/index';

With this configuration, accessing http://localhost/codeigniter/custom-route will route to the Welcome controller's index method.

Step 4: Access Your View

Start your CodeIgniter development server (if it's not already running) and access the URL associated with your controller and method. For example, if you are using the default route, access http://localhost/codeigniter.

You should see the content from your welcome_message.php view displayed in your web browser.

That's it! You have successfully created and loaded a view in CodeIgniter. You can create additional views and controllers to build more complex web applications.

Muhammad Alfaiz
Alfaiz 6 months ago
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x