How to access static assets in CodeIgniter?

2020-06-28 01:30发布

问题:

I am using CodeIgniter for a Project .

Folder Structure - htdocs/NewProject/application

I created a controller called Home - applications/controllers/home.php

I created a view - applications/view/index.php

I can access the index.php without issue .

My route is

$route['default_controller'] = "home";

I can access localhost:8888/NewProject - which takes me to home#index

I have put some css and images folders inside views folder . How do i access the images and css ?

Trying to access NewProject/css/xxx.css leads to not found error .

Is there any alternate folder where I should add these static files ? Do I need to add anything to the routes file ?

回答1:

Make the structure something like this

root (is your root directory)
    /application
    /system
    /static
        /images
        /css
        /js

Change your base URL in config.php

/*
  |--------------------------------------------------------------------------
  | Base Site URL
  |--------------------------------------------------------------------------
  |
  | URL to your CodeIgniter root. Typically this will be your base URL,
  | WITH a trailing slash:
  |
  | http://example.com/
  |
  | If this is not set then CodeIgniter will guess the protocol, domain and
  | path to your installation.
  |
 */
 // use this if your project is in root
$config['base_url'] = 'http://example.com/';

// use this if your project is in folder/subfolders
//$config['base_url'] = 'http://example.com/newproject/liveproject/';

Autoload URL helper in autoload.php

/*
  | -------------------------------------------------------------------
  |  Auto-load Helper Files
  | -------------------------------------------------------------------
  | Prototype:
  |
  | $autoload['helper'] = array('url', 'file');
 */

$autoload['helper'] = array('url');

In your view file

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>static/style.css" />

<img src="<?php echo base_url(); ?>static/images/myimage.jpg" alt="" />

Hope this helps. Thanks!!