Loading css value from database

I am currently working on a CMS site using the Yii Framework where the user can edit the main background color used in the site. When I load the page, I need to query the CSS (background color) value from the database, put the result in cookies, and then use those values ​​in my CSS file.

To use PHP variables and cookies in the CSS file, I renamed the CSS file from main.css

to main.php

and added: header("Content-type: text/css; charset: UTF-8");

at the top.

The problem is that when I open the page for the first time, the colors I get from the database are not loading. I am using a validator element and validated the CSS file, but the background color definition is not. It only appears after I have refreshed the page once.

Please tell me what I did wrong? Any help is appreciated. The relevant code is shown below.

Inserting request and cookies into protected/components/Controller.php

:

public function beforeControllerAction($controller, $action)
{
    if(parent::beforeControllerAction($controller, $action))
    {
        $prog = Programs::model()->find(array(
            'condition'=>'id_program = :program',
            'params'=>array(
                ':program'=>Yii::app()->params->programCode,
            ),
        ));
        Yii::app()->request->cookies['color1'] = new CHttpCookie('color1', $prog->main_color1);
    }
}

      

CSS file:

<?php
header("Content-type: text/css; charset: UTF-8");
$color1 = $_COOKIE['color1'];
?>

#header
{
    background-color: <?php echo $color1; ?>;
}

      

+3


source to share


1 answer


Based on what you indicated, there are two probabilities

1.Your cookie value is set after the main.php request

You should have your css file loaded, main.php

AFTER you set the cookie. For this you can use Controller::beforeRender

. In your protected/components/Controller.php

you can have this

public function beforeRender($action)
{
    $color = Yii::app()->request->cookies['color1'];

    $prog = Programs::model()->find(array(
        'condition'=>'id_program = :program',
        'params'=>array(
            ':program'=>Yii::app()->params->programCode,
        ),
    ));
    Yii::app()->request->cookies['color1'] = new CHttpCookie('color1', $prog->main_color1);


    return true;
}

      

Just make sure nothing bad (like loading css) happens while doing this find

. In case of overwriting.



2. Your css is cached

To load your css dynamically at the location where you load main.php

(maybe your layout) you have to add something like this:

<link rel="stylesheet" type="text/css" 
href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.php?q=<?php echo microtime(1);?>">

      

This way you can be sure that your css is loaded dynamically. However, this is similar to the built-in one <style>

. Your code is a little more organized and takes a little longer.

+2


source







All Articles