Tigrex
Tigrex

Reputation: 27

Include PHP variables into CSS

So... I have a index.php file in which I defined a class named 'rectangles'. This class has color and size.

I created a variable named

$rectangle($rectangle=new rectangles('red',25);).

And yes I did the

<link rel="stylesheet" type="text/css" href="test1.css" />.

Then I created another file "test1.css" in which I defined the 'div' tags like this:

div{
      color:<?php echo $rectangle->color; ?>;
    }

I tried to put in this .css file <?php include 'index.php'; ?> but my variables from the .php file won't work no matter what I try.

Of course I tried to change the test1.css to test1.php and try to do that but it only works with variables I set in the test1.php not from the index.php.

Well I don't know if I explained my problem well but I hope you understand...
Thanks in advance.

Upvotes: 0

Views: 2738

Answers (3)

Devin
Devin

Reputation: 7720

What you want to do is very common and done every day in CMS development. You can use SASS or LESS, you can include the style as internal CSS in your PHP files as Rodrigo answered, or you can do this:

1) Add this to your header:

<?php header("Content-type: text/css; charset: UTF-8"); ?>

2) in the same folder of your file, add a .htaccess file with this content:

AddHandler application/x-httpd-php .css

2.b) Alternatively, you can set your Apache config file like this:

AddType application/x-httpd-php .php .php3 .php4 .php5
AddType application/x-httpd-php-source .phps
AddHandler cgi-script .cgi .pl

Now, you can be a happy camper and add PHP variables to your CSS files

Now a comment: I do this almost every day, and I use the method in the answer by Rodrigo, because I do work for 3rd parties, mainly building customizable themes, so this method, while better if you're in control of your server, is not possible if you don't know who will get the theme. I'm mentioning this for anyone seeing this answer so they can ponder the pros and cons

Upvotes: 3

vusan
vusan

Reputation: 5331

One another way:

<head>
<style>
<?php include 'style.css'; ?>
</style> 
</head>

style.css

div{
 color:<?php echo $rectangle->color; ?>;
}

But in this case, style will not work if we link from <link> tag because of php code on it. So we may also rename style.css as style.pcss or something to avoid confusion that the file is only css or php embedded css file.

Upvotes: 0

Rodrigo Morbach
Rodrigo Morbach

Reputation: 388

You can do that by adding your style into your php file. So, in your php or phtml file you can do something like this:

//php code . . .

<head>
<style>

div{
 color:<?php echo $rectangle->color; ?>;
}

</style> 
</head>

It won't work in a file with a .css extension.

Hope it helps.

Upvotes: 1

Related Questions