Store CSS in PHP variable? - php

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.

Related

PHP Require method doesn't show any CSS style

I'm recently doing a website for a school project. In order to organize my work, I create a tree folder that keeps all the work organized. It is similar like this:
Back-Office
Pages
Home
home_test1.php
home_test2.php
home_test3.php
Login
Folder_Login
login.php
logout.php
Resources
CSS
style_home.css
style_navbar.css
style_footer.css
JS
script_home.css
script_navbar.css
Sections
navbar.php
footer.php
After all, with the require() method available in PHP, I want to call the "navbar.php" file to the "home_test1.php", "home_test2.php" and "home_test3.php", but the CSS style that is connected with the file "navbar.php" ("style_navbar.php"), doesn't display.
I've tried to change the path of the CSS style in the file "navbar.php" when I require() to the other file ("home_test1.php") and the CSS style shows up, but wont display in other file with a different path. How can I make this work dynamically? Sorry for long post and bad English grammar.
Thank you in advance.
You need to set your css and js files with absolute path instead of relative path
$dir = realpath($_SERVER["DOCUMENT_ROOT"]);
<link rel="stylesheet" href="<?php echo $dir.'/resources/css/style_home.css'; ?>" >
Without physically seeing you code it is quite hard to debug however there is an "obvious" answer that I'll suggest as a starting point.
The important thing to remember is that PHP and HTML are processed in completely different places. PHP executes on the server and should be used to build a full HTML "document" which it gives to the client/browser. The client/browser then reads the document provided and renders it according to HTML standards.
Calling require() will tell PHP to get the file and slot its contents directly where it was called and as it is a CSS file it will need to sit within the style tags. With a lot of modern browsers, if you use require on a file outside of the html tags, the content will be dumped at the top of the screen or simply ignored due to invalid syntax.
Alternatively if you would like to simply use tell the browser to include the CSS file, you could use the good old method of using <link rel="stylesheet" href="/path/to/file">. It's good to know when and when not to use PHP.
PS: You have .css files in your JS directory.
In PHP, there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:-
$_SERVER['DOCUMENT_ROOT']
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
<link rel="stylesheet" href="<?php echo $path.= '/Resources/CSS/style_navbar.css';?>" />
?>

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.

External stylesheet (css) in php

I have looked through 4-5 post on stackoverflow regarding this without solving my problem.
I have a php file and want to use the css stylesheet I have for the other HTML files.
Right now it looks like this:
<div style="height: 600px;">
<?php
echo "<link rel='stylesheet' type='text/css' href='stylesheet.css' media='all'/>";
session_start();
$admin = $_SESSION['admin'];
$author = $_SESSION['author'];
?>
<?php if ($admin == true AND $author == true) { ?>
<p id="confirmationText"><?echo "Thank you for your message! <br>You should have received a confirmation email. We will contact you soon."; ?></p>
<?php } ?>
</div>
It is not working; the p id="confirmationText" text does not get formatted. interestingly, when I just open the file locally without apache server, it will get HTML-formatted.
What to do?
CSS style links sometimes don't work properly if they aren't in the <head> ... </head> area. The best practice would be to just declare that echo statement up
there.
Try opening your page in a browser, and clicking 'inspect
element' on that place where your stylesheet is linked, and see if you can see any problems there. Often browsers just render things strangely. It can give your clues as to what's wrong.
Why are you linking the stylesheet before your session_start command? Perhaps this might just be causing an output buffer error. Try putting your link at the end of the PHP code.
Honestly, sometimes even the "best practice" and "cleanup" methods of fixing code, won't work. You can just use a little css hack. It's bad practice and a bit depreciated but I've been writing code for years and this just makes life so much easier: Instead of linking a stylesheet externally .... imbed the style directly.
Add this piece of code to your file:
<style>
<!-- change the path to the correct one, though. I have no clue where your file is, in the filesystem, I'm just guessing, here -->
<?php include($_SERVER['DOCUMENT_ROOT'] . "/stylesheet.css"); ?>
</style>
Can you open the stylesheet in your browser?
Also, why are you echoing a stylesheet in a div, and not in the head?

Passing data to dynamic CSS file?

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(); ?>">

Yii including CSS and JS files

I've been reading on this quite some time...and i'm puzzled -
Can you help on what is the difference between:
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/some-file.css');
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/some-file.css
Is it a performance issue, or just different syntax?
Thanks,
Danny
registerCssFile always registers the file between the <head> tags, even if you call it somewhere in a view.
This is helpful if you care about HTML validation (a <link> in <body> is invalid), but still want to include a CSS file in a view.
registerCssFile actually aids performance, because the CSS is registered only when you want it (and need it).
The way you are using it, it is identical. To verify this, check the source of the page (in your browser) and check the statement that Yii::app()->clientScript->registerCssFile creates.
However, clientScript lets you control the position of the script in the HTML file. Check out: http://www.yiiframework.com/doc/api/1.1/CClientScript#registerScriptFile-detail and look for POS_HEAD, POS_BEGIN, POS_END.
What is probably more important is this: In the MVC philosophy, you want to have everything related to HTML-output in your view-file. Yii::app()->clientScript lets you add CSS and JS files from within your view files. And that is where you want it.

Categories