Sempoinus Sempoinus - 1 month ago 5
CSS Question

CSS in PHP with mysql

I have little problem with connection style.php to db

<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
header("Content-type: text/css; charset: UTF-8");
$Color = "#000000";
$Test = "#555000";
?>
#header {
background-color: <?php echo $Test; ?>;
width: 500px;
height: 500px;
}
a{
color: <?php echo $Color; ?>;
}


this code is working perfectly.
and when i do something like this:

<?php
header("Content-type: text/css; charset: UTF-8");
$Color = "#000000";
$Test = "#555000";
?>
#header {
background-color: <?php echo $Test; ?>;
width: 500px;
height: 500px;
}
a{
color: <?php echo $Color; ?>;
}


here #header{} this won't work but a{} will work.
can i somehow make it work?

Answer

If you want generate CSS from PHP use it in .php file like this:

<html>
<body>
<?php
   $Color = "#000000";
   $Test = "#555000";
?>
<style>
#header {
   background-color: <?php echo $Test; ?>;
   width: 500px;
   height: 500px;
}
a{
    color: <?php echo $Color; ?>;
}
</style>
</body>
</html>

Do not use it in .css file. You can also generate new .css file from .php file with fopen() and fwrite() PHP functions and then just with meta tag include it into webpage.

Creating .css file from PHP

<?php
$Color = "#000000";
$Test = "#555000";
$css = '#header {
    background-color: '.$Test.';
    width: 500px;
    height: 500px;
}
a {
    color: '.$Color.';
}';

$myfile  = fopen("generated_style.css", "w") or die("Unable to open file!"); // Open file
fwrite($myfile, $css); // Write CSS
fclose($myfile); // Close file
?>
Comments