Home >Backend Development >PHP Tutorial >Can PHP Be Executed Within a CSS File?
Integrating PHP into CSS
Question: How can you execute PHP scripts within a CSS document?
Answer:
To run PHP code within a CSS file, you need to change the file extension to .php to enable the server to recognize it as a PHP file. Once you make this change, you can link to the file as a regular CSS file. Additionally, ensure that the following header is set at the beginning of the file:
<code class="php"><?php header ("Content-type: text/css"); ?></code>
Example:
Consider the following code:
/* CSS file: styles.css */ body { background-image:url(../../images/<?php echo $theme.'/'.$background; ?>);}
<code class="html"><!-- HTML file: index.html --> <link href="css/<?php echo $theme; ?>/styles.php" rel="stylesheet" type="text/css" /></code>
By modifying the CSS file extension to .php and including the proper header, the PHP code within the CSS can be executed and the background image can be dynamically set.
Note: It is recommended to use shorttags for efficiency and readability:
<code class="php">body { background-image:url(../../images/<?=$theme.'/'.$background; ?>);}</code>
The above is the detailed content of Can PHP Be Executed Within a CSS File?. For more information, please follow other related articles on the PHP Chinese website!