How can I use PHP code in a CSS file

2.1k views Asked by At

I want to find an image source from a MySQL database and assign it to a css style. I just changed the .css extension to .php.

It does work with XAMPP and runs everything I want, but when I uploaded my code in cpanel it didn't work correctly.

I used this code in the css file:

Top of page:

<?php include '../Connections/Base.php'; ?>
 <?php header("Content-type: text/css; charset: UTF-8"); ?>

Some styles:

.box {
    overflow: hidden;
    display:block;
    border:4px solid #171717;
    position:absolute;
    cursor: pointer;
    float:left;
    display: inline-block;
    zoom: 1;
    background:url(<?php 
        $query = "SELECT imape_path FROM MyTable WHERE number='5' LIMIT 1";
        //echo $query;
        if ($result = $mysqli->query($query)) {
            while ($row = $result->fetch_assoc()) {
                echo $row['imape_path'];
            }
        }
 ?>) no-repeat;
}

How can I fix this problem?

2

There are 2 answers

0
Oliver Gondža On BEST ANSWER

Personally, I do not think this is the right problem to address.

The whole point in separating markup and styles is to simplify things. I see very little value in separating it so rigidly you have to mix css, php and sql instead (you just moved the same problem elsewhere).

My suggestion is to configure .box's background using inline css in the html page itself and inject the url as any other value:

<div class="box" style="background: url('<?php ... ?>')">...</div>
0
ryansin On

You could try keeping the .css extension on the file with PHP code, and setting a rule in .htaccess to parse the file as PHP (source).

<FilesMatch "^.*?style.*?$">
SetHandler php5-script
</FilesMatch>