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.
Related
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.
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.
tl;dr - I'd like to know if it is possible to pass an object into a PHP file with CSS headers, such that I can use this object to manipulate various CSS attributes.
What I'm attempting to do, is allow my PHP/CSS file to interact with the other objects/php files in the webpage, e.g. menu item objects. My ultimate goal is to use PHP in the CSS file to count the number of menu items, and apply the appropriate width value in order to space them out evenly on the page.
I use a very simple color based example below to demonstrate my understanding so far...
I understand that for basic usage of PHP in a CSS file, one can do something like:
<?php header("Content-type: text/css");
$dkgreen = '#008400';
body {
background:<?=$white?>;
}
?>
I also understand that OO PHP can be used to achieve a similar thing, e.g.:
class css {
function __construct($args=array()) {
foreach($args as $key => $field) {
$this->{"$key"} = $args["$key"];
}
return $this;
}
}
$css = new css(
array(
bgcolor => '#00FF00',
fgcolor => '#000000',
)
);
body {
background: <?php echo $css->bgcolor; ?>;
color: <?php echo $css->fgcolor; ?>;
}
Results of experimentation
1) OO style
I firstly attempted to make my css class create a singleton object for the CSS, which I tried to retrieve using $css = css::singleton(), along with the getCss() function, instead of $css = new css(...). The idea was that I wouldn't simply initialise another css object which would be useless to me. Attempts to get the values for bgcolor and fgcolor using:
$css = css::singleton();
$css->getCss()->bgcolor;
were unsuccessful.
2) altering the href in the link tag à la style.php?bgcolor=00FF00&fgcolor=000000
This worked beatifully, when I could easily type $bgcolor = $_GET['bgcolor'];, but doesn't seem to me an elegant solution.
Ideally, I'd like to retain an Object-Oriented approach, but if that's not possible, I'll happily settle for a POST approach, (i.e. allow me to use $bgcolor = $_POST['bgcolor'];) to avoid filling up the source code with ugly parameters in the link tag.
I'd also wish to avoid creating multiple .css files, if that is at all possible.
Any tips?
Many thanks,
Owen.
The easiest way to do this is to make your CSS file a PHP file, and link to it.
<link href="style.php" rel="stylesheet" type="text/css" media="all" />
Then, you parse all your code and dump it out at the end.
$css = ''; # all of your compiled CSS after you do what you need to
header("Content-type: text/css");
print $css;
exit;
Now, your CSS is being parsed how you want it to be, and it's being served as CSS.
I don't think it's possible, and that doesn't fit the purpose of CSS.
Edit:
Well basically, CSS is suppose to contain data that apply a style on a well defined structure. So CSS should not even have variables ( this is a big debate ). The "good theorical way" to solve your problem is to generate html code with proper id and classes, so that you don't have to make any calculation using CSS: you only have to apply a style.
Furthermore:
CSS file are made to be cached. If they change all the time, you may have cache problem, or need to ask the file not to be cached. The you might need to generate inline CSS using PHP, but not a CSS file itself.
Quick and should be simple question, but i cant find the answer!!! So im trying to make a universal header called header.php. Now the only problem is that some pages have 5 css style sheets while others have only 2. And some pages have 5 js links in the header while some only have 1. How do i account for this variability in css and js links in the header? Am i suppose to use if statments? Variables? Thanks!
Consider combining resources to single ones. This will minimize HTTP requests which is a good practice.
Instead of creating a static header.php, create a function to include javascript files dynamically. For example, you need only jquery & jquery ui js references for page1, so you call
include_js('jquery', 'jquery-ui')
where include_js is your function which will insert respective JS files.
Similarly, in page2, you need assume you need jquery & jquery.fancybox
include_js('jquery', 'jquery.fancybox')
You should be using a setup like this. Of course, you might want to make it so that the styles are included from your view and not your controller. Can't give a better answer without knowing your setup.
In your controller
$styles_for_layout = array();
$scripts_for_layout = array();
//and whenever you need to include a script in for your particular view
$scripts_for_layout[] = 'script_for_page.js';
$styles_for_layout [] = 'style_for_page.css';
headerp.php
<?php if(!empty($styles_for_layout))?>
<?php foreach ($styles_for_layoutas $style) : ?>
<link rel='stylesheet' href='<?php echo $style ?>'>
<?php endforeach; ?>
<?php endif; ?>
<?php if(!empty($scripts_for_layout))?>
<?php foreach ($scripts_for_layout as $script) : ?>
<script type='text/javascript' src='<?php echo $script ?>'>
<?php endforeach; ?>
<?php endif; ?>
Loading all the CSS and JS file in every page won't matter much as after a first load, they will be cached and not retrieved again.
Therefore, you could just bundle them and not worry if you really need a particular file in the current page or not.
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