user1481317
user1481317

Reputation:

Codeigniter PHP require_once works but load->view doesn't

I am facing a weird problem for 1 hour, I searched it on internet and this forum but couldn't find the Solution that I am looking for. I am using codeigniter framework to develop a small product. So here is my problem:

I have a controller named music.php which simply loads the template view:

/* music.php */
public function index()
{
    $data['main_content'] = 'admin/music/list';
    $this->load->view('admin/template', $data);  
}

The content of admin/template.php is as follows

<?php $this->load->view('header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('footer'); ?>

the header.php and footer.php are located on the same folder as template.php. Now when I tried to access the file, browser shows the error "Unable to load the requested file: header.php". But instead if I use require_once("header.php") it works fine. Can any one solve this problem

Edit 1: my route.php is

$route['default_controller'] = "homepage";
$route['404_override'] = '';
$route['admin'] = 'admin/music';

Upvotes: 0

Views: 6240

Answers (4)

Sachin Kale
Sachin Kale

Reputation: 66

The above answers are right. But this answer is for the ones who are using codeigniter 4. You need to do the following:

<?php echo view('admin/header'); ?>
<?php echo view($maincontent); ?>
<?php echo view('admin/footer'); ?>

Upvotes: 1

ChrisKoe
ChrisKoe

Reputation: 1

I had the same issue. I assume it has to do with the missing constructor function. At least, this solved the problem for me. Add this as first function in your controller:

public function __construct()
{
    parent::__construct();
}

Upvotes: 0

Sameer Mahant
Sameer Mahant

Reputation: 114

From above code, it seems you have header.php and footer.php file in your application/view/admin/ folder. Therefore use :

<?php $this->load->view('admin/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('admin/footer'); ?>

Upvotes: 0

No Results Found
No Results Found

Reputation: 102735

All calls to load->view() use paths relative to application/views, not relative to the file calling it. (They also do not take your routes into consideration at all)

If header.php and footer.php are located in the same folder as template.php (the master template you are loading) you still need to reference the full path, starting with admin/:

<?php $this->load->view('admin/header'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('admin/footer'); ?>

Upvotes: 1

Related Questions