Php In Css, Javascript

How to include php code in a css, javascript files under webapp/css folder?

You can’t include PHP in CSS or JavaScript files.

You need to create PHP files and include CSS or JavaScript code in those newly created PHP files,

and then include those PHP files instead of CSS, JavaScript files.

<link rel="stylesheet" href="/css/style.php"/>

<script src="/css/script.php"></script>

You can write php in javascript however. But we don’t recommend that so the better option would be include your css and javascript in php file.

How do you write php in JavaScript? I’m interested to know.

The file should be .php however. I mean to say, in php file, inside of javascript you could use php variable.

you could also tell php to parse js files, but that would decrease site performance since the js files won’t be cached by the browser anymore.

Its always better to generate javascript and css with php, and leave your .js and .css files static


You say it is not recommended to write php in javascript. But when you have to call a php variable in javascript, you do it. I would like to know if there is any other way to do it.

I sometimes use this in javascript to call a php variable:

 var = <?php echo $myvar; ?>; 

Is there another way to do it?


Yes, using php in javascript is not well recommended. I am just saying when situation arises that we have to do; there is a way we could do using php variables inside javascript. In yii, you create javascript as a string and register it using Yii::app()->clientScript->registerScript. So, since js is registered as a string, you could create that string using php variable as well.

Thanks, if it is not too much asking: can you give me an example?

the example would be something like this:

Yii::app()->clientScript->registerScript('KadastraleCodeWidget_script', 'var myPhpVar = ' . $myPhpVar . ';', CClientScript::POS_HEAD);



Thanks for your answer. I have a question:

What is the difference between app()->getClientScript and app()->clientScript?


well, as far as I know is the result equal, only app()->clientScript uses the magic __get() method while app()->getClientScript() does not

Thanks Hyprion :)