0

I'm trying to use php inside my css but server return php-code as is <style>p{background: url(<?php echo hello;?>)};</style>

I see url(<?php echo hello;?>) in my inline style with browser console. It doesn't matter do I place text/css header inside the code or not, quoted or double-quoted the php section.

But this style work properly on another server. Maybe there is any setting that doesn't allow use php this way?

2
  • 1
    Where are you adding this code? Commented Sep 24, 2017 at 4:14
  • 1
    It will works fine in file by extension .php Commented Sep 24, 2017 at 4:15

3 Answers 3

3

It seems that the problem is that you're trying to put php code into a .css file and your server is not configured to run php from this file type.

If you're using Apache, you can try to add this line into your .htaccess file (create one in the root if you don't have it)

AddType application/x-httpd-php .css

However, note that this action may cause some security issues.

Sign up to request clarification or add additional context in comments.

3 Comments

It will also slow the server down, since it will now look for php code in all css files. The solution I'd prefer is the other way around - I'd stick the css into a php file.
Yep, it's true, but the question was about running php in css files. Obviously you can use .php files to provide dynamic CSS, but that is the different question.
indeed. I just felt it was worth mentioning in case the OP wasn't aware of this. Since the files end up looking more or less the same, it's a low-cost decision with potentially expensive ramifications down the line.
0

If you give your CSS file a .php extension (e.g. style.php) you can include PHP code in it. You may also want to send a CSS MIME type in the header, e.g.:

header( 'Content-Type: text/css' ); 

Comments

0

I think you are doing the thing wrong way with a wrong syntax.

$hello= "'img/example.jpg'";
<style>p{background: url(<?php echo $hello;?>)};</style>

You are missing the quotes here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.