February 28, 2013

Code Igniter : base_url() at CSS file doesn't work

Question by Esgi Dend HigherCloud

base_url() doesn’t work at CSS file…

here’s my php :

<link rel="stylesheet" type="text/css" href="<?=base_url()?>css/style.css"/>
<body>
</body>

here’s my css/style.css :

body {
  background:#356aa0 url(<?=base_url()?>img/background.png) repeat-x;
  color:#fff;
}

the text color change to white, but the image doesn’t show up…
if i use url(../img/background.png), it show up…
but when i open url localhost/project/index.php/control/function/var1/var2, it doesn’t show up…

It’s Solved, Thanks every one… :]

i make php file at view folder like this :

<?php header("content-type: text/css"); ?>

body {
    background:url(<?=base_url()?>img/background.png);
}

and i load the php file i just make with function at controller, and then i link it :

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

It’s work, Thanks guys…

Answer by Starx

CSS file does not get parse as PHP file. If you really want to do something like that, rename your file as styles.php

OPEN the page and add

header("content-type: text/css");

This tells the page to be treated as a text based CSS file. Then you can simple echo your remaining CSS like

echo "
body {
....
....
";

To fix the base_url() not being accessible from styles.php set a session variable to keep that. You can keep this on your index.php of codeignitor.

$_SESSION['base_url'] = base_url();

Now, use this inside styles.php.

background: url("<?php echo $_SESSION['base_url']; ?>"/../../some.jpg");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!