Loading css value from database - php

Currently I am working on a site CMS using 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 value (background colors) from the database, put the result to 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 add: header("Content-type: text/css; charset: UTF-8"); on the top.
The problem is, when I opened the page for the first time, the colors I get from the database are not loaded. I use inspect element and checked the CSS file, and the background color definition is not there. It only appears after I refreshed the page once.
Please tell me what did I do wrong? Any help is appreciated. The relevant code is provided below.
Query and Cookies insertion in 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);
}
}
The CSS file:
<?php
header("Content-type: text/css; charset: UTF-8");
$color1 = $_COOKIE['color1'];
?>
#header
{
background-color: <?php echo $color1; ?>;
}

Based on what you have stated, there re two probabilities
1. Your cookie value is set after your main.php is requested
You should have your css file, main.php loaded AFTER you have set the cookie.
In order to do that you can use the 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 be sure that nothing bad (like loading the css) happens at that find. In case of overwrite.
2. Your css is cached
In order to have your css loaded dynamically in the place you load main.php (probably your layout) you should 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 way is just like having inline <style>s . Your code is a bit more organized and a bit more time consuming.

Related

CSS file ignored when loaded with include in PHP

I am writing my own MVC implementation and I am facing a problem including local CSS files. Basically all requests in my applications are going to a method which is decomposing them in order to get a controller and action. For example:
localhost:8888/items/list
this request will be redirected to my index.php where I have:
Application::start($_SERVER['REQUEST_URI']);
Then the request is decomposed to get the controller 'items' and action 'list'
So far all good and I didn't realise the problem as I was using bootstrap from CDN. However now if I include in my html something like:
<link rel="stylesheet" type="text/css" href="/css/style.css">
This will go to my method again and it will not work.
What I tried is to check if the URI contains 'css' and if it does just include the file with:
if(preg_match('/css/',$uri)){
include "../webroot/$uri";}
This worked in terms of loading the css but the css is ignored. Also I get
"Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost:8888/css/style.css"."
The problem is even bigger if I try to include images although with images at least I am able to display them but again through 'include'. Any ideas how to fix this ?
P.S I know that the problem is most likely because the css is loaded as text file, however I don't know how to get this working with my current setup
Try header("Content-type: text/css; charset: UTF-8"); with file_get_contents instead of include like this
if(preg_match('/css/',$uri)){
header("Content-type: text/css; charset: UTF-8");
if(!$file = file_get_contents("http://localhost:8080/project_name/webroot/$uri")) return 0;
echo $file;
}

Right way for pass variable php to css in Wordpress

i need to passing variable from php to css for customize style from custom theme option.
The only way i have find is create file.css.php
and working good.
But my question is: This is good for website load a file .css.php ? or can have some other problem, like speed or seo?
There are some other good methods?
Thx
Indirect solution:
It sounds like you want to include different CSS behavior based on user selection. Let's say that user selection is stored in a variable $foo. Just include it in an element's class like this
<?php
$foo = 'option-1'; ?>
<div class="<?php echo $foo; ?>"></div>
There are also two direct solutions to your issue:
1. Use inline CSS or CSS in your file's page head:
<style>
div.button { color:<?php echo $bar ?>; }
</style>
2. Use a PHP file as CSS. This would look like:
<link rel="stylesheet" type="text/css" href="/style.php">
Then you can use PHP variables right inside your CSS file. Just make sure you change the content-type back to CSS at the beginning of the file like this:
<?php header("Content-type: text/css; charset: UTF-8"); ?>
This method is a little bit unconventional, but it'll work without any speed or SEO drawbacks.

PHP Variables in CSS not working

I have the following code for my html file:
<html>
<head>
<link rel='stylesheet' href='css/style.php' media = "screen"/>
</head>
<body>
<h1 id="foo">My h1 foo element</h1>
</body>
<html>
And for my php file:
<?php
header("Content-type: text/css; charset: UTF-8");
$asd = '#0000ff';
?>
h1#foo {
color: <?php echo $asd;?>;
}
I've followed some tutorials and this is the simplest one i could make but somehow the output is not working the way it should be. Did i miss anything?
P.S. if i was gonna use php variables in css, can it be sort of dynamic? i mean inside the php body, can i overwrite the value of the php variable used in css and the output would change?
Help would be much appreciated ty!
Works fine for me ^^
Use this syntax:
cssman.php
<?php
ob_clean();
header('Content-Type: text/css');
header('Cache-Control: no-cache, must-revalidate');
error_reporting( 0 );
// These are just to show you can use dynamic values and such:
$type = isset($_GET['type']) ? $_GET['type'] : '';
$theme = isset($_GET['theme']) ? $_GET['theme'] : '';
/** Simply print or echo your css here **/
ob_end_flush();
?>
Try your output first, by navigating to the .php file manually. If there is no content at all, there is most likely a mistake in the PHP code, for debugging you could add error repporting (don't forget to also ini_set('display_errors',1), else errors will only be logged).
Then add it to your view:
your view
<style type="text/css">
#import "/Library/Stylesheets/cssman.php?type=cms" screen;
/* any aditional files here aswell */
</style>
you can do it like
echo"
<style>
h1#foo {
color: ".$asd.";
}
</style>
";
Firstly, to include a php file this syntax is absolutely wrong:
<link rel='stylesheet' href='css/style.php' media = "screen"/>
To include a Css file we use following syntax:
<link rel='stylesheet' href='css/style.css' media = "screen"/>
and include a php file we use:
<?php
include_once "a.php"; // this will include a.php
?>
Instead of using PHP to manage the CSS, you may want to consider one of the CSS preprocessors which are specifically intended for that purpose. It also dissociates your client side code from the server side technology.
http://lesscss.org/
https://learnboost.github.io/stylus/
http://sass-lang.com/
Another approach worth considering is to break up the CSS into several files. You can have a common file that applied to all pages on all devices, one that contains the colors, another that manages the layout, perhaps some device specific ones.
The code you post works as expected. The title with id=foo goes blu. The only problem is that it doesn't use the .css extension for a css file. To solve this you could put in css folder a .htaccess with instructions to Apache Web Server to use Php interpreter also for the css files (look this link).
However probably for dynamic-ly change it from php, you mean change the value (e.g after a user input or some other events).
BUT If I understand well your question the answer is no.
Php can only preprocess your page, it can't modify dynamicly your page after it is loaded by the browser from the user. In addiction, using the code above your variable $asd can only be changed in the style.php AND before that it is used in the code.
I suggest you to use javascript instead, it's a lot easier. Use some javascript library like jQuery, to that kind of job.

CodeIgniter - pass variables to CSS

I'm rewriting website on Code Igniter, and i need to load external TTF. MySQL db points path to that TTFs. Can I pass somehow these variables to CSS and make foreach loop to 'loads' these fonts.
I tried
$this->load->vars($data);
First, deal with serving dynamic CSS. My site has a controller called "resource" which allows me to serve CSS, JS, etc. (maybe images in the future). It loads views based upon the segments passed to it in the url.
So, when http://mysite.com/resource/css/main.css is requested:
My Resource controller (.../controllers/resource) handles any specifics of data handling (as is general with an MVC controller). It then loads:
A generic view: ".../views/resources/css.php", passing it the name of the desired css file. This view prints out the header, specifying the Content-Type (important!) and any other generic stuff. Then it proceeds to load:
The actual CSS file specified, here ".../views/resources/css/main.css.php".
It's a little overkill, but allows for a lot of flexibility, like you sound like you need.
Controller:
...
$segments = $this->uri->segment_array();
array_shift($segments); // remove the first two
array_shift($segments);
$content['stylesheet'] = $segments[0] . ".php"; //e.g. main.css.php
$content['data'] = array(); //Font data, etc
$this->load->view('resources/css.php', $content);
..
Generic resources/css.php
This loads up the actual .css.php stylesheet
<?php header("Content-Type: text/css"); // This is key! ?>
/* MySite CSS File (c) 2011 bla bla */
<?php
$this->load->view("resources/css/$stylesheet", $data);
echo "\n";
?>
Specific resources/css/main.css.php
<?php echo "/* I can use PHP in my CSS! */\n"; ?>
body { background-color: <?=$data['bg_color']?>; }
p { font-family: <?=$data['p_font_fam'];?>; }
You probably need to understand how you retrieve data from db and how you display them:
http://codeigniter.com/user_guide/database/index.html
good luck
EDIT:
what you need is probably something like that:
after you have retrieved the links from database and let's say you called them $ttf_links
<?php
foreach($ttf_links as $link){
echo "<link rel='stylesheet' type='text/css' href={$link['row_name']} media='screen' />"
}
?>
and then call the fonts you need in your css
Passing variables to a CSS doesn't work for as far as I know.
I have read something about CSS templating with PHP, but I can't find the link anymore. Will update this answer as soon as I found the link. But you could look for it yourself as well.
Update
Found it!: http://www.barelyfitz.com/projects/csscolor/
The easiest way I see you doing this is with file level CSS and changing values the usual way.
A workaround would be to use CSS in the page itself to load the fonts.
Here is the answer , I have implemented this and works fine
https://ellislab.com/forums/viewthread/220105/#1014374

drupal_add_css not working

I need to use drupal_add_css to call stylesheets onto single Drupal 6 pages. I don't want to edit the main theme stylesheet as there will be a set of individual pages which all need completely new styles - the main sheet would be massive if i put it all in there.
My solution was to edit the page in PHP editor mode and do this:
<?php
drupal_add_css("/styles/file1.css", "theme");
?>
<div id="newPageContent">stuff here in html</div>
But when I view source, there is nothing there! Not even a broken CSS link or anything, it's just refusing to add the CSS sheet to the CSS package put into the page head.
Variations don't seem to work either:
drupal_add_css($path = '/styles/file1.css', $type = 'module', $media = 'all', $preprocess = TRUE)
My template header looks like this, I've not changed anything from the default other than adding a custom JavaScript.
<head>
<?php print $head ?>
<title><?php print $head_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
<script type="text/javascript" src="<?php print base_path() ?>misc/askme.js"></script>
<!--[if lt IE 7]>
<?php print phptemplate_get_ie_styles(); ?>
<![endif]-->
</head>
Why is this function not working?
It is not quite clear where you are selecting the template that you have in your example. If you are selecting it from a module then you can just use drupal_add_css in the module rather than the template.
If you have your own theme you can use template_preprocess_page and put logic in there to add the relevant CSS (you can also use it to select the template to use).
I have noticed something weird and it might fix your problem:
drupal_add_css( drupal_get_path('theme','themname') . '/working.css','module' ,'all' , false );
drupal_add_css( drupal_get_path('theme','themname') . '/path/to/folder/notworking.css','module' ,'all' , false );
The first one will work ebcause the style it in the main them folder
The second line will not work because the style is in a sub folder !
Edit:
i think it did not work because i did not write the path the the style file properly :S so please disregard my answer
drupal_add_css( drupal_get_path('theme','test') . '/pages/subpage/style.css','theme');
is working
This function wont work in templates. The reason is that the variable $styles which will hold all the stylesheet html will already have been generated at this point, so drupal_add_css wont work as it adds to that. if you want to do this in your theme, you would probably have to add the css file manually
<link rel="stylesheet" ... />
The other way would be to use drupal_add_css in a module, but you might have a hard time adding the correct css files on the pages you want.
It's possible to use drupal_add_css() inside your template.php file; this page has a good example of how to do just that.
Thanks for the link, wyrmmage. That's very useful. I think the rest of the code in the page is unneccessary. You probably just need these since drupal 6 already automatically check for file existence:
drupal_add_css(path_to_theme() . '/css/yourcss.css', 'theme');
// Add the following to regenerate $styles.
// This is needed for template_preprocess_page() since css is already generated at this point.
$variables['styles'] = drupal_get_css();
Answer was very much to use the CSS Injector module - great little addon!
Here is an excerpt from its project page:
Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme. The CSS is added using Drupal's standard drupal_add_css() function and respects page caching, etc. The 2.x brach leverages CTools so CSS can be included with Feature changes (ie. CSS that improves the look of a View can be packaged with the View).
This code inside template.php works for me:
function alagna_preprocess_page(&$vars) {
drupal_add_css(path_to_theme() . '/header_1.css', 'theme');
$vars['css'] = drupal_add_css();
$vars['styles'] = drupal_get_css();
}
explained:
alagna is the theme name
header_1.css is the css file required.
drupal_add_css is expecting a path relative to base path whereas drupal_get_path does not return the path relative to base path.
global $base_path;
drupal_add_css($base_path . drupal_get_path('module / theme','name') . "/styles/file1.css", "module / theme");
You can choose between module and theme accordingly.
Try this
common.inc drupal_get_css($css = NULL)
Parameters
$css: (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
$css = $vars['css'];
// unset the system css files
$unset_css = array
'modules/system/system.css',
'modules/system/system-menus.css',
);
foreach($unset_css as $css_f) {
if(isset($css['all']['module'][$css_f])) {
unset($css['all']['module'][$css_f]);
}
}
// add css
$css['all']['theme'][drupal_get_path('theme', 'openpublish_theme') . '/css/style.css'] = true;
$vars['styles'] = drupal_get_css($css);

Categories