CodeIgniter + CSS

2019-02-13 11:50发布

问题:

Good Day, I'm learning CodeIgniter with Smarty. My CSS file is stored in

/App01/application/views/css/main.css

To link my CSS I use:

<link rel="stylesheet" type="text/css" href="http://localhost:88/APP1/application/views/css/layout.css" media="screen" />

But CSS is not applied on my page. When I open CSS URL, I get a message:

Forbidden
You don't have permission to access /APP1/application/views/css/layout.css on this server.

Please, what am I doing wrong? I'd like to keep my CSS together with the view because in future I'd like to learn how to create multiple themes and I thing the CSS should be kept within the theme folder.

Can I replace URL path to CSS file with some Smarty variable so that when I move my application I do not need to change CSS URL path in templates manually?

Thank you in advance! Vojtech

回答1:

Anything in the /application folder of CodeIgniter should be considered out-of-bounds. For the best security, you should actually consider keeping /application above your www or public_html folder in a structure such as this:

– application
    – controllers
    – models
    – views
    – ...
– system
    – core
    – libraries
    – ...
– public_html
    – index.php

This makes your application code safer.

I’d advise creating your client-side scripts and CSS in a public folder. For example public_html/css and public_html/js. Or, if you wanted to go down the theme route, possibly name each CSS file as the name of the theme, so you’d have css/theme1.css and css/theme2.css.

If your site will always work from the root of a domain, then you can just use:

<link rel="stylesheet" type="text/css" href="/css/layout.css" media="screen" />

But if you feel that you’re going to be moving all sorts of things around, then consider preparing the file location in your controller before sending it to Smarty.

$this->load->helper('url');
$this->smarty->assign('css_file', base_url("css/theme1.css"));

That will return:

http://localhost/app1/css/theme.css

Or whatever your CodeIgniter URL is.



回答2:

This will help to link css to codeigniter.

The link_tag is used to link resources and you can use helper function. For example html helper, url helper, email helper, etc.

In your controller you have to create a function something like

<?php 
class Home extends CI_Controller{
    public function helper(){
        $this->load->helper('html');    
        $this->load->view('index');
    }
}
?>

And your index.php in view folder use link_tag keyword.

<html>
<head>
<title></title>
<?php echo link_tag('App01/application/views/css/main.css');?>
</head>
<body>
    <?php 
     .......
    ?>
</body>
</html>


回答3:

Try adding a symlink to your servers document root folder. (www/public_html/htdocs)

cd (document root folder)
ln -s (/App01/application/views/css) .

This way you can access your css folder and keep the current structure.