PHP Variables in CSS not working - php

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.

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.

Will a PHP value travel through an include and then through a linked php stylesheet?

I have a index.php page, which has a header.php page included in it, which references a style.php file.
The page I am working on has the following in the head:
<?php
$page = "testimonials";
include 'header.php';
?>
The header.php has if statements to set the correct style sheets and variables for the nav bar etc and also includes as I said, the style.php sheet using the following code:
<link href="style.php"
rel="stylesheet"
type="text/css">
My question is, I am trying to use an if statement in style.php as below:
<?php
header("Content-type: text/css; charset: UTF-8");
if ($page == testimonials){
print "margin-top: 5%;\n";
}
?>
The if statement does not seem to be working however as this is not being printed, and I am wondering if this is because I can't pull the value through the include, then through the stylesheet href?
Thinking about it, I think that as stylesheets are not included like .php files, this may be the reason, could someone just confirm this is the case, or suggest a better work around?
I was thinking of perhaps putting some CSS in the <head> of the PHP include for my file under an if statement, but I feel that may not be best practice.
You cannot do this .... the link element is not an actual server side include. If you want to give the style.php file access to the variable in the header.php page, pass it via the query-string to the style.php page in the link tag.
<link href="style.php?page=<?=$page?>"
rel="stylesheet"
type="text/css">
Then in the style.php page, read the value from the query-string parameter:
<?
$page = $_GET['page'];
?>
Then, you can use it in an if statement inside the style.php page:
if ($page == 'testimonials'){
Yes. If you include some file, it is the same, as if you write the code from that file there, instead of include.
Your Problem is this:
if ($page == testimonials){
It should be
if ($page == 'testimonials'){
Cheers

PHP session is not read in css file

I have two files, one is a php file where a session is set, the source is included below.
An .htaccess file is in place to make sure css will be parsed like a php file,
I have verified that this works, but no session data can be read from style2.css
index.php:
<?php
session_start();
$_SESSION['bgimg'] = 'picture.jpg';
?>
<head>
<meta charset="utf-8">
<title>Index</title>
<link rel="stylesheet" type="text/css" href="style2.css">
</head>
....
the other is style2.css:
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
print_r($_SESSION);
?>
body {
background: #fff;
background-image: url("<?php echo $_SESSION['bgimg']; ?>");
}
....
I think your session cookie might not be sent along with .css requests, so the session cannot be fetched.
css will be parsed like a php file,
This is a terrible idea!
Instead use mod_rewrite to rewrite style2.css to a PHP script
RewriteRule ^style2\.css$ generate_style.php
Other than that your session code looks fine, maybe PHP is just confused about the .css file.
In general, passing css files though the php interpreter is not the best idea.
Css is meant to be static, cached data with styling information.
As it seems that you want to dynamically set a background image of one specific element, I suggest using the style attribute in html like so:
<body style="background-image:url(<?= /* php code here */ ?>);"></body>
If, on the other hand, you want to change styling based for example on your login status, I suggest using html class attributes as flags and using the class selector in css:
Example CSS:
p {
/* formatting without login */
}
.login p {
/* formatting with login */
}
Example php
<!-- snip -->
<body <? if(/* check login here */) { echo 'class="login"'}?> >
<!-- snip -->

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.

Tell from where a .php file has been included?

Does anybody know of an automated way of telling whether a PHP script is being called directly (as a HTML page), or as a JavaScript, or as a CSS Stylesheet?
Without GET variables, or setting a flag in the file ( that is what I am doing right now).
Just curious.
EDIT: Some background because it was asked for in answers: The reason why I want this is a framework that I use when serving HTML pages as well as when serving CSS files. This frameweork has a custom error handler. When I'm in JS "mode", I would like to throw errors as a JS alert(). When I'm in CSS mode, maybe a red body background or something. I would like to avoid working with flags (?mode=css) or constant definitions for the sake of code cleanness, but several answerers have confirmed that there is no "magic" way of finding out what a resource is being used for.
So you want to distinguish between:
<link type="text/css" rel="stylesheet"
href="http://example.com/path/to/php-file.php" />
<script type="text/javascript"
src="http://example.com/path/to/php-file.php"></script>
Or simply opening
http://example.com/path/to/php-file.php
in a browser.
There's no flag set in these cases to distinguish how the file was called. You can examine the $_SERVER array by doing <?php print_r($_SERVER); ?> and they should be identical in each case.
I take it you're adding ?mode=css or ?mode=js to the end of the url -- that seems like a logical way to switch what kind of output you want. Then in the code you can do:
$mode = (isset($_GET['mode']) ? $_GET['mode'] : '';
switch ($mode):
case 'css':
// css
break;
case 'js':
// js
break;
default:
// default
endswitch;
If I understand you correctly, you have a page which calls itself, (like this):
<?php // page.php
if (is_called_as_js()) {
header('Content-Type: text/javascript;charset=utf-8');
echo "alert('hello');";
exit;
} elseif (is_called_as_css()) {
header('Content-Type: text/css');
echo 'body { color: green }';
exit;
}
?>
<html>
(...)
<script src="page.php"></script>
<link rel="stylesheet" href="page.php" />
In that case, no, there's no way to tell - the browser sends a request saying GET /page.php. No intent is mentioned - just "give me the page and the browser will decide what to do with it". (yeah, yeah, there is Accept and whatnot, haven't seen a modern browser actually using this feature to say "give me this page as CSS", most just say Accept: */*)
If you insist that all your output, be it JS, CSS, or HTML, should be generated with one file, I suggest an URL rewriter (assuming Apache HTTP server, this would be mod_rewrite; most platforms offer this functionality in some way or another). Example using mod_rewrite:
# .htaccess
RewriteEngine On
RewriteRule ^css/(.*) /page.php?type=css&file=$1 [L]
RewriteRule ^js/(.*) /page.php?type=js&file=$1 [L]
This way, request to /css/style.css will look like page.php?type=css&file=style.css when your script is run, similarly for /js/foobar.js.
(Technically, you're still using GET variables to find out if the result is supposed to be HTML,JS,or CSS; but it's not visible to the users, plus you get around some older browsers' limitation "if query string, don't cache or cache brokenly")
No.
There isnt really any reason why you should need to do this though. Either you should have very differnt php files being called as css or js files or you should pass get parameters. They way you layout your code should make this unambiguous.
Although it's not entirely clear to me why you'd want to generate such different filetypes through a single script, you could use different wrappers:
<?php // js.php
define('TYPE','javascript');
require('page.php');
?>
<?php // css.php
define('TYPE','css');
require('page.php');
?>
<?php // page.php
if (!defined('TYPE')) {
?>
<script src="js.php"></script>
<link rel="stylesheet" href="css.php" />
<?php
} else if (TYPE == 'javascript') {
header('Content-Type: text/javascript;charset=utf-8');
?>
alert('hello');
<?php
} else if (TYPE == 'css') {
header('Content-Type: text/css');
?>
BODY { color: red }
<?php
}
?>
You're still getting to page.php in the end, but you now know with what intent.

Categories