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");
...

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