Passing data to dynamic CSS file? - php

This is more a question of what browsers will do, rather than the back-end architecture.
I am using codeigniter and have a controller setup to handle assets (CSS, JS, and images), and at the moment I am simply processing the PHP out of CSS files and presenting them as CSS files to the browser, so www.mysite.com/asset/home.css will call the asset class and generate the CSS file for home from a single file.
I would like to make the request for the CSS files more dynamic, so that the request will determine multiple files that should be combined, and then passed to less.php for parsing and minimization.
Taking into account issues of caching, what would be the best method of passing variables to the CSS class? Flat Link URI variables? Traditional GET URI? I could use a database to reference a given name for its components, but isn't that a lot of overhead?
Any thoughts or opinions are welcomed!
++ How would browsers handle something like standard.menu.comments.css?
+++ I ended up going with a URI string appended to the file. It's not as clean I would want, but it appears to be working. I will likely move to a flat slash separated URI parser soon to clean up the request lines. Thanks for your help!

You can create a file style.php with the following header:
<?php header("Content-type: text/css"); ?>
And link this style in your template:
<link rel="stylesheet" type="text/css" media="screen" href="style.php?color=red">
Then you can import some stylesheets in your style.php:
#import ("someStyle.css");
Or you can pass some $_GET variables and create conditional styles:
<?php
if ($_GET['color'] == 'red')
{
echo ".myBlock {background: #ff0000;}";
}
else
{
echo ".myBlock {background: #00ff00;}";
}
?>
If you just don't want your .css files to be cached, append random $_GET variable to your linked style:
<link rel="stylesheet" type="text/css" media="screen" href="style.css?<?php echo time(); ?>">

Related

browser ignores css printed by php

I have a stylesheet link that looks like below:
<link rel="stylesheet" href="/example/get_page.php?location=bla.css" id="main_ss" />
get_page.php just gets a URL using file_get_contents():
if (isset($_GET['location'])) {
echo file_get_contents('/example/styles/' . $_GET['location']);
}
I can see that the stylesheet file is being fetched properly (for example the text of the file is showing in firebug when I expend the link tag) but for some reason it is ignored by the browser. If I just fetch the CSS file directly of course everything works.
The code can be seen here: www.specman-verification.com/example/bla.html
Any leads? I'm at loss here.
Add the Content-type header like this (do this before you output anything):
header("Content-type: text/css");
Your code is just trying to load the script get_page.php. To load the CSS file you need:
<link rel="stylesheet" type="text/css" href="/example/bla.css" />
(or similar depending on the actual path to your CSS file). In other words the href attribute needs to specify the path to your spreadsheet file, not the HTML page file.
You need to do it the right way. I understand what you're doing here. You need a good mechanism to dynamically load external CSS and have the result display normal html in the browser output.
Follow the instructions on this url: http://www.warpconduit.net/2009/05/12/dynamically-load-css-and-js-files-using-php/
This will at least get you to have a mechanism to load external css file with php dynamically. You're definitely missing steps in your code.

Store CSS in PHP variable?

I'm a novice php learner, I was experimenting how to link different php files dynamically. While experimenting, I realize I can create variables in my php files and make my template files echoes out the html I need without editing my template files......
for example:
Within about-me.php page, I have included my header.php and footer.php using
<?php include ('includes/header.html'); ?>
<?php include ('includes/footer.html'); ?>
then I create a variable
$page_title = 'CompanyABC';
and echo out in the header.php
$page_title = 'South Asia Exact';
Now my question is can I do this to my inline css also?
for example, I have create a variable, that store all my inline css:
$page_inlinecss = "#SAEcontentR div#certification_certificate {
margin:0 auto 0 auto;
width:580px;
height:464px;
}\n";
then I echo out in my header.php like so:
<style type="text/css">
<?php echo $page_inlinecss; ?>
</style>
I have tried it and it works, but I want to know is it the right way to do it?
There isn't a right way to do inline CSS
Your code will work, it will produce a valid page, and it will look absolutely fine to the user. BUT you shouldn't do it that way.
So, why shouldn't you do it that way?
Maintainability is the main reason that you shouldn't handle CSS this way. It is far easier to manage a separate CSS file than to pick through PHP code looking for CSS rules to change.
It looks like the data you're storing is static, the point of a variable is to store data that can change. Things like the name of the website (Company ABC) are unlikely to change during the execution of the script, so you should include them in the static HTML template.
On top of this are issues like caching (most browsers cache .css files, saving you bandwidth) and accessibility (screen readers may not know how to deal with inline styles & js).
How should you handle dynamic styles?
One way to handle dynamic styles (that is -- styles based on information which will be different on different page loads) with a combination of PHP and CSS is to define class styles in your external document and then use PHP to apply them.
For example, put this in styles.css:
span.greentext { color: #0f0; }
And this in your PHP file:
<span class='<?php echo ($someCondition) ? "greentext" : null; ?>'>Some text</span>
Or, if you have more styles to handle:
Alternatively, you could load a specific stylesheet upon a condition:
<?php if($someCondition): ?>
<link rel="stylesheet" href="styles/conditional.css" type="text/css" media="screen">
<?php endif; ?>
Hope this helps, and please don't use inline CSS, or variables, unless necessary. You'll thank yourself for it when you have to change the site 5 months down the line.
Can you do this? Yes.
Should you do this? Ehh. (No. was a bit harsh...)
Better to store the CSS filename in a php variable, then in the header add:
<link rel="stylesheet" href="<?php echo $this_page_style_sheet; ?>" />
There is no right or wrong in this case.
You may store the CSS in a string and echo it as you see fit. Or you may even embed it in your includes/header.html file. It's up to you.
Personally, if it is a collection of CSS rules, I would keep it in its own CSS file, and just echo the filename when needed.
$css_filename = "/path/to/rules.css";
// ... etc etc
<link rel="stylesheet" href="<?php echo $css_filename; ?>">
This is a beauty and a pitfall of the way the system works. You can do that, it works and it doesn't seem to present any immediate and glaring security issues. I don't know if that was an intended use of PHP, but it works so if it fits your situation you can use it. The pitfall comes when enough of these little workarounds are used that eventually a security issue could arise somewhere, but I don't recall CSS ever being used as a vector for an attack.
You can do this to generate dynamic css
file css.php
<?php
header("Content-Type: text/css");
echo 'p {color:red}';
?>
html (not complete but it should work cross browser)
<link rel="stylesheet" href="css.php" type="text/css" />
<p>This should be red</p>
Some more strict/uptight folks might say that proper CSS doesn't need variables, yadda yadda.
Personally I think if this works, then it's a clever way to add some ease-of-use to CSS. I'm all for it.

How to load a css in CodeIgniter?

I'm new to programming. I want to fetch the css saved in DB and load in a php file. I'm using CodeIgniter. After loading the css, I want to link to it as an external css. I tried following, but it is not working.
EDIT:
defaultCss.php is the file in which I want to load the css.
$strTemplate.="<link rel='stylesheet' type='text/css' href='".base_url()."user/defaultCss.php'>"
While, I view the page source it gives "Page not found" error.
Below are my controller and view code.
function loadDefaultCSS(){
$this->load->model('UserModel');
$this->UserModel->loadDefaultCSS();
}
View :
if(isset($strTemplateStyles) && $strTemplateStyles!="") {
echo $strTemplateStyles;
}
Model function :
function loadDefaultCSS($strTemplateStyles){
$data['strTemplateStyles']=$strTemplateStyles;
}
Why this is not working ? what is the issue ?
You can use template library for codeigniter.
It provides more flexibility for handling views, loading js and css files.
Also it provides an option for splitting the views into sections like header, content, footer etc. The template library link i have provided above is easy to use and integrate.
It also has very good documentation.
In the above template library the css and js files can be loaded as follows (write below code in controller) -
For loading css files -
$this->template->add_css('path to css file');
For loading js files -
$this->template->add_js('path to js file');
For detailed documentation you can refer above hyperlink.
Well the name of your controller action is loadDefaultCSS, so I would expect the URL for the generated stylesheet to be: (assuming your controller is indeed called User)
base_url()."user/loadDefaultCSS"
Does this work?:
$strTemplate .= '<link rel="stylesheet" type="text/css"
href="'.base_url().'"user/loadDefaultCSS">';
I can see a few strange things in your code:
You should not use .php in your CI URLS
How can your view possibly get the style of the user when you're not passing it to the view from your controller?
How do you know what user it concerns? I assume you have not posted all your code?
What happens if you actually open the stylesheet URL that you generate? Does it throw a 404? A CI error?
The Best way to load css is to pass css paths from controller to view and render it from view in large application we its not good practice to load everything in header it can cause performance issue
login_view.php / view
css code
<?php
if(!empty($css_files)){
foreach ($css_files as $css_path) {
?>
<link rel="stylesheet" href="<?php echo $css_path;?>">
<?php
}
}
?>
login.php /controller
$data['css_files'] = array(
base_url('assets/bootstrap/css/bootstrap.min.cs'),
base_url('assets/plugins/iChecksquare/blue.css'),
'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css');
$this->load->view('login',$data);
same technique you can use for javascript libs
note that sequence of the files are sensitive

Cakephp, dynamically write variables into css file upon load of view?

I'm working out a process to save actions that occur from jquery in my view in cakephp.. I figure an easy way to load the saved values, such as the width and height for a DIV, would be to have cakephp echo a variable as their width / height in the css file, much the same way it would do this in the view file.. I guess I'm not sure exactly where to look for info on this, if its in the cakephp cookbook I guess I'm missing it as I don't see how to do it in there.. any advice is appreciated.
This is actually pretty easy (and powerful), and can be done without the aid of CakePHP.
First, make a new file in your webroot called css.php. At the top of that file put the following:
<?php header("Content-Type: text/css"); ?>
Now, link to this file in the head of your layout, just as you would a normal CSS file.
<link rel="stylesheet" href="/path/css.php" type="text/css" />
And there you have it, a dynamic CSS file. You can pass information to it like so:
<link rel="stylesheet" href="/path/css.php?c=red&fw=700" type="text/css" />
CLARIFICATION: To access the variables mentioned above, you would use the $_GET variable in the CSS file. Take a look at the link tag above. To access those variables in the css file, you would do something like this:
.class {color:<?php echo $_GET['c']; ?>;font-weight:<?php echo $_GET['fw']; ?>;}
UPDATE: After viewing the link you posted about the CakePHP HTML Helper, I realized that there is a better way to do this if you intend to pass a lot of variables to the css file.
Create a new model and controller called DynamicStyle and DynamicStylesController (or something similar). Then, make a new layout file called css.ctp that all of this controller's views will use. Declare the content-type header statement in that layout file.
The last step would be to link to a method in that controller from the head of your standard layout header.
Now you could make a database table of css rules and use those with the HTML helper in the css view.
I just realized CakePHP has something for this as well:
http://book.cakephp.org/view/1440/style
So this may come in handy for anyone who comes across this in the future

Dynamic CSS and Javascript

How does one create Dynamic CSS and JavaScript On-The-Fly (using PHP).
This needs to be done as different pages have different set of elements sometimes, so wrapping and sending a large CSS/JS everytime would be overkill.
And why do many sites have link tags like this:
<link rel='stylesheet' type='text/css' href='css/style.css?pg_id=43&post=62'>
How does the CSS come to know the GET parameters?
Since this might involve URL rewriting or using the header function, please supply short examples
So, there's a few different approaches you can take here. First, if you have access to apache's virtualhost files, you can set CSS to be read by a php interpreter. I've never done this and wouldnt exactly recommend it but an example is:
<VirtualHost *:80>
AddType application/x-httpd-php .css
</VirtualHost>
This can also be done in your .htaccess file.
Alternatively, you can make a link like
<link rel='stylesheet' type='text/css' href='css/style.php?pg_id=43&post=62'>
and put
<?php header("Content-type: text/css"); ?>
as the first line.
I've never considered Vinicius' technique but I don't doubt that has its own set of advantages and disadvantages too.
PS - sometimes GET variables are uses for caching purposes (or actually to prevent caching by appending the current unix timestamp to the css link with php like
<link href="style.css?<?php echo time()" type="text/css" rel="stylesheet" />
A request to a .css or .js file can be redirected to a PHP script using, for example, an .htaccess (in Apache), so even if the src attribute is "style.css", it's actually a PHP script that is responding to the user.
Your CSS and Javascript files are cached, I would not recommend serving different style sheets / js files unless they're >200KB or so in size.
And yes, you can reference any server-side page with parameters (.php or whatever extension) as long as it returns the correct Content-Type for that file.
Sidenote: Usually if you have parameters and are dynamically serving files in this manner, I believe they will not be cached automatically unless you set it up to do so.
Simple example:
<link rel="stylesheet" type="text/css" href="/css.php?color=wide-red">
<?php
header('Content-Type', 'text/css; charset=utf-8');
$colorScheme = (string)$_GET['color'];
switch ( $colorScheme ) {
case 'wide-red':
$bgColor = 'c0c0c0';
$fgColor = 'ffffff';
$width = '1280px';
break;
case 'normal-gray':
$bgColor = '333333';
$fgColor = 'ffffff';
$width = '960px';
}
break;
}
?>
body {
background:<?php echo $bgColor;?>;
color:<?php echo $fgColor;?>;
width:<?php echo $width;?>;
}
You can use echo, you can use a templating system, you can pull in other css files with file_get_contents, key thing is you need to send the right Content-Type, grab the right parameters and have a default fallback if no parameters are given.

Categories