Home > Article > Web Front-end > How Can I Successfully Execute PHP Code within My CSS Stylesheets to Dynamically Display Images?
How to Execute PHP Commands within CSS Stylesheets
Question:
I need to implement PHP code within my CSS stylesheet to display a DB-generated background image:
<link href="css/<?php echo $theme; ?>/styles.css" rel="stylesheet" type="text/css" />
body{ background-image:url(../../images/<?php echo $theme.'/'.$background; ?>);}
I attempted adding the following header, but it merely outputted the code in HTML format:
<?php header ("Content-type: text/css"); ?>
Answer:
To successfully run PHP code inside CSS, follow these steps:
Change the file extension to .php:
Switch the extension of the CSS file to .php so the server can execute PHP commands.
Change:
<link href="css/<?php echo $theme; ?>/styles.css" rel="stylesheet" type="text/css" />
To:
<link href="css/<?php echo $theme; ?>/styles.php" rel="stylesheet" type="text/css" />
Include the correct header:
At the beginning of your .php file, include the following header:
<?php header ("Content-type: text/css"); ?>
Shorten PHP tags:
For convenience, use the shortened PHP echo syntax:
Change:
<?php echo $var; ?>
To:
<?=$var; ?>
By following these steps, you will be able to run PHP code dynamically within your CSS stylesheets.
The above is the detailed content of How Can I Successfully Execute PHP Code within My CSS Stylesheets to Dynamically Display Images?. For more information, please follow other related articles on the PHP Chinese website!