I have a script, and I have to include image path using PHP code in the CSS stylesheet. But when I try to adding PHP code in my CSS class background-image URL () property file nothing occurs! Is it possible?
div.home-banner {
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url("<?php echo APP_HOME_BANNER_IMAGE; ?>");
}
CodePudding user response:
You would essentially have two options:
Move this CSS code
This would mean removing this code from the .css
file and putting it in the .php
page in a <style>
element. Then PHP wouldn't see any difference between this or any other code on a .php
page.
The downside, of course, is that you'd be re-coupling some de-coupled CSS/HTML code. Which isn't terrible, but could be distasteful depending on personal preference.
Enable PHP on .css
files
You could configure your server to also process .css
files through the PHP engine, just as it does with .php
files. PHP can process any files you like, it just only processes .php
files by default.
The downside here is that you'd always be invoking the PHP engine for all .css
files, when the vast majority of cases don't require it.
Which approach you choose is up to your personal preference. I'd personally prefer the former, as it's a more obvious thing to support in ongoing code (since the latter is rarely done and unexpected).
CodePudding user response:
There are multiple ways to solve that issue.
I like to import css in a php file to use php in it. It is pretty easy to declare the header type:
header("Content-type: text/css;charset=UTF-8");
now we can use css and php in the style.php:
<?php
header("Content-type: text/css;charset=UTF-8");
include("more.css");
echo '
.whatever {
}
';
?>
That way you can link the file like a regular .css file
<link rel="stylesheet" type="text/css" href="css.php" media="screen"/>
Now comes another theory, but i never tried it and it can be completly wrong. We can use the AddType in a .htaccess file to allow php in files like a .html, so in theory that should work too:
AddType application/x-httpd-php .php .css
But tbh, i never tried if that would work.