Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PHP inside css file [duplicate]

Tags:

I have CSS file and I want to refer some image paths in that files in PHP varaible format. Then I refer that css file inside a html file. Following are my file

CSS file

<? header ("Content-type: text/css");?>
 body{ margin:0px; font:9px/11px "Tahoma", Arial, Helvetica, sans-serif; color:#010000; 
 background:#f3f6e1 url(<?php echo base_url().'public/';?>images/body_bg_1.gif) repeat-x 0 0}

HTML file

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="css/layout.css" media="screen"> 
</head>

Other things. Can you explain me how to do this ?

like image 288
Malintha Avatar asked Oct 12 '13 19:10

Malintha


2 Answers

If you're able to rename your CSS file "layout.php", there's no need for all of these workarounds:

Your layout.php file would look like:

<?php header("Content-type: text/css; charset: UTF-8"); ?>
body{ margin:0px; font:9px/11px "Tahoma", Arial, Helvetica, sans-serif; color:#010000; 
background:#f3f6e1 url(<?php echo base_url().'public/';?>images/body_bg_1.gif) repeat-x 0 0}

Your HTML files would look like:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="css/layout.php" media="screen"> 
</head>

This question is very similar: Include: css with php file extension?

like image 183
Will Hannah Avatar answered Nov 03 '22 19:11

Will Hannah


Perhaps the return value of base_url() does not end in the path separator.

With that in mind, try this:

@import url("<?php echo base_url().'/public/';?>css/layout.css");

(Notice the slash before "public")

  • Check the source of the page via your browser's "view source" or similar, and check if the path in the @import is correct

or

  • Use a request logger similar to Chrome's devtools' "network" tab to see what URL your browser is trying to load the imported CSS file from.

You also view the CSS via your browser to identify whether the contents are being correctly built. If you see <?php inside the response, you'll need to make Apache treat the CSS file as if it was PHP.

You can add something similar to the following into your .htaccess file:

<FilesMatch "\.css$">
    SetHandler application/x-httpd-php
    Header set Content-type "text/css"
</FilesMatch>

You should ensure that the "mod_headers" Apache module is enabled to allow the use of the Header directive.

Although, personally I would rename such dynamic stylesheets to have a .php.css extension. This will have no effect, but then Apache can be configured to only pass the dynamic stylesheets to the PHP preprocessor.

<FilesMatch "\.php\.css$">
    SetHandler application/x-httpd-php
    Header set Content-type "text/css"
</FilesMatch>
like image 43
Spooky Avatar answered Nov 03 '22 18:11

Spooky