add a php variable to a css statement! - php

I would like to include the following in my css style statment. is it possible?
<option selected value="" class="" style= background: url<?php some php variable; ?></option>

If that portion of HTML code is in a .php file, yes, it is possible : PHP does just generate the output, no matter if the textual data is actually corresponding to CSS, HTML, JS, ...
Note though that your HTML code, here, is not quite OK : you are missing quotes arround the content of the style attribute, you should add parenthesis arround the url, and should use selected="selected".
Also note that you need to echo the content of the variable -- and not just use its name.
So, basically, you should have something like this :
<option selected="selected" value="" class=""
style="background: url(<?php echo $your_variable; ?>)">
text of your option
</option>

Martin's answer is just fine, but I felt I should I point out that they way you are mixing CSS into the HTML isnt a good idea. Keeping the CSS part out of HTML file is always a better suggestion.
In case you would like the stylesheet to be generated for each request depending on certain values, (for eg, you need to pull values from the database), you could simply have a CSS file, and inside PHP tags you could pull the data and put it in the right place, like you would do for HTML.
For eg:
In HTML:
<link rel="stylesheet" type="text/css" href="style.php?user=abc" />
Style.php
<?php
header('Content-type: text/css');
$var = /*Get the background color setting for user abc*/;
?>
.wrap{
background-color:<?php echo $var; ?>;
}

That's what PHP was born for
Try echo $var;

Related

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.

How to insert css code in php?

I know how to insert html code in php using print <<<HERE HERE; construction. It means I can insert a link to css file. But is it possible to insert css code itself?
There are a couple of ways you can achieve this.
Lets say you have an anchor tag My Href and you want to add CSS to it based on certain instances.
You can easily echo that css into the anchor element like so:
<a <?php echo 'style="float: left;"'; ?> href="..">My Href</a>
The output would be:
<a style="float: left" href="...">My Href</a>
You can do this with almost any HTML element.
Now let's say you have a predefined CSS class you would like to echo into an anchor tag element.
Let's say you have this CSS class in your stylesheet:
.floatLeft {
float: left;
}
You can simply echo that class into the anchor element like so:
My Href
Which the output of that would be:
My Href
Yes. It is possible.
There's actually two different ways.
Method 1: Inject PHP into your actual CSS. This is done by making your file .php, using regular HTML and CSS, and then doing as such:
.someclass {
/* Some code */
<?php // Whatever you wanna inject
?>
I have performed this many times, and no one knows. It may not be the most efficent way, but it's also sometimes better than doing...
Method 2: Escape your quotes and lines.
Use:
echo("/* Your css code here */ \ (to escape the line return
/* Whenever there is a quote, make sure to do the following: \" ");
If you don't escape the quote, PHP will think you're ending the string. That's bad, because the rest of your text gets ignored.
ADDITIONAL NOTE: You don't have to use print for echoing HTML. Echo works too.
Yes, you can easily do that. You can either do it in the CSS file like 'ilarsona' said, or you can do it in the HTML file itself.
For example:
<!DOCTYPE html>
<html>
<head>
<title>The Title</title>
<style>
p {<?php *Insert dynamic styles here* ?>};
</style>
</head>
<body>
<div style=<?php *Insert styles here* ?>> </div>
</body>
</html>

Sharing a code fragment all over the website

So, if I have a website containing two or more webpages with some same code fragment (e.g. side menu or top bar), how can I store this fragment in one place for using by all the webpages on the website?
I tried to put that repeating code to separate php file, like:
<?php echo "<div id='menu'> ... </div>";
and then just use
<?php include "menu.php" ?>
but problems occur with double-quotes inside double-quotes (considering I have PHP and JS scripts inside that "central" one, it's even more trouble), interpretation and so on.
What should I use (preferable HTML and PHP tools) to achieve that "code sync"?
Why are you echoing HTML?
How can I put double-quotes inside double-quotes?
You can escape the double-quote by prepending a backslash:
echo "<div id=\"some-id\">";
But, you're dealing with the wrong problem!
You're going along the right lines with re-using code, but you don't need to echo HTML. Any HTML outside of PHP tags will parse as regular HTML anyway, so just do it like this:
<div id='menu'>
...
</div>
Then require_once('menu.php'); to import the file. This way, you won't have to mess around with escaping nested quotes.
What if I have dynamic content in my menu?
Good question, then use something like this:
<div id='menu'>
<?php foreach($menuitems as $menuitem): ?>
<div id='<?php echo $menuitem['id']; ?>'>
<?php echo $menuitem['text']; ?>
</div>
<?php endforeach; ?>
</div>
By keeping the PHP and the HTML in separate tags, you create code which is easy to parse, easy to read and easy to maintain.
Similarly, don't use inline JavaScript
Keep your js in separate files, and call it from within your HTML like this:
<script src="script.js"></script>
You know you can just include 'menu.html' or include 'menu.php' without echo just using html tags and adding any php functionality inline like you would normally.

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.

Large block of HTML in a PHP block

I'm using PHP to make my page more dynamic through query passing however I have a big chunk of HTML code that needs to have dynamic content inside but I don't know how to go about doing that without printing every statement:
One part in HTML:
<div class="review">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/rotten.gif" alt="Rotten" />
<q>Expect no intelligence or subtlety here, but if you're willing to put up with the sheer ridiculousness of it all, you might enjoy wallowing in Bekmambetov's shameless exhibition of narrative lunacy and technical fireworks in this movie.</q>
</p>
</div>
<div class="personal">
<p>
<img src="http://www.cs.aub.edu.lb/hsafa/cmps278/hw2/critic.gif" alt="Critic" />
Frank Swietek <br />
<span class="italic">One Guy's Opinion</span>
</p>
</div>
The above code is for a single review however there could be any number of reviews which I am already taking a count of but I am also changing the image, quotes and text for all the reviews.
Is there a way of including all the tags without printing them all?
The regular way is to "close the php tag" and then reopen it after the HTML:
// php code here
?><html code goes here><?php
// php code here
However, there are a couple other ways. One is to use include.
// php code here
include('template.file.php');
// php code here
and inside your html code, you use have something like this:
<htmltag><?= $php_value ?></htmltag>
You can even use include within a function.
Alternatively, you can use a template system like Handlebars, Mustache, or Twig. Or you can just continue to build large strings, which is what I do. I set up templates, merge them with data to produce strings, and then emit the strings. The main thing I gain from using the templating system is that I can save up the strings to emit them at the end, and thus, have the ability to alter the HTTP header before my output is sent. If I used include() or code blocks, the code is emitted immediately, and I cannot modify HTTP header values.
Additionally, by building up the strings, I can save them to files and use these precalculated chunks to improve the site's speed.
<?php
//PHP code section
$wolrd = 'world';
?>
We are back in HTML
Hello <?= $world /* and some PHP echoing with a 'short tag' on same line with HTML*/ ?>
Suggested reading:
http://www.smarty.net/ (I'm not a fan but you should be aware of it)
MVC - Model - View - Controller
You should only be using PHP to print your dynamic content
<img src="<?php echo $image_url; ?>" alt="<?php echo $image_alt; ?>" />
You can close PHP and start it again at any point
<?php
$string = "hi";
?>
<p>Lot's of HTML</p>
<?php
echo $string;
?>

Categories