Embedding PHP code in a CSS file - php

Can we embed php code in a css file. I need to add conditions to css properties.
styles.css
<?php
if($suserid == 2)
{ ?>
.proverb { border:0px solid blue; margin-left:34px; width:250px !important; margin-top:6px; } <?php
}
else
{ ?>
.proverb { border:0px solid blue; margin-left:0px; } <?php
}
?>

Your request is bad practice. Do not proceed.
While it is technically possible to do this, you should look into alternatives. Do not dynamically generate CSS files. They will be cached by your browsers, and dynamic changes will not be propagated.
Instead, make special-case classes that you can add to the HTML. Your CSS would become:
.proverb {
border: 0px solid blue;
margin-left: 0px;
}
.proverb.user-2 {
margin-left: 34px;
width: 250px !important;
margin-top: 6px;
}
In your HTML-generating code you can have:
<div class="proverb <?php if($suserid == 2) echo "user-2"; ?>"></div>
This will add the user-2 class if the user id is 2, and gives the same result as what you wanted in your example.

A file is considered PHP by the handlers your webserver attaches to a file type or file extension. If a file is considered PHP, the contents will be executed as PHP code.
Assuming you're using apache, you can add the php handler to CSS files by adding the following in your VirtualHost file or in your .htaccess file:
<Directory "/path/to/your/css/dir">
AddType application/x-httpd-php .css
</Directory>
The only downside is this changes the output mime-type to text/html of all css files in the given directory. Therefore you have to override the mime-type so browsers know you're sending css in stead of html. Trough PHP you can use: <?php header('Content-type: text/css'); ?> on the first line of every css file.
Keep in mind changing the handler to php for css files does put more stress on your server, since every file has to be parsed before it can be sent to the output buffer. Therefore it's easier and better to just add an extra class to your html output and adjust your css accordingly, like #Rizier123 suggests.

It's possible.
First you have to tell your web server to serve *.css files through the PHP ISAPI module, then you can embed the code.
But this is not a good practice and I'd advise not to do so. There are better solutions, like SASS and LESS.

Related

Issue with css url request

I'll try to explain the issue the best I can: I have two css uploads methods. The first one is with link rel and is working fine.
The second one (for performance issues), goes inside the css file and print directly the css into the page.
<!-- <link rel="stylesheet" href="<?php echo URL_SITE; ?>style/index.css" /> -->
<style>
<?php
$urlstyle = URL_SITE.'style/index.css?m='.(int) IS_ON_MOBILE;
$style = file_get_contents($urlstyle);
echo $style;
?>
</style>
There is absolutely no doubt about what is loaded. Those two methods returns the same css.
As an example we can use this part of the css
.wrapper-accueil .scroll:before {
content: "";
display: block;
width: 30px;
height: 30px;
background: url("../assets/img/picto/arrow-down.svg") no-repeat center center;
background-size: contain;
}
As you can see, there is an url inside.
When trying to load the css with the first method, the path is fine. Everything works fine.
But here comes the issues, when I try my second method writting this css inside the file where it's called. The url path of the css is wrong. (I shouldn't have the first ../ to make it works.
But here is the thing. Even if this code shouldn't be working with the second method. The file is loaded properly with no problem. And I can't understand why it's working. (And the cache is cleared ne doubt about that neither).
More stranger things, when I upload the website on server and i'm no longer in localhost, then there is indeed an issue and the file isn't found as it should be.
So working in localhost while it shouldn't. Not working in server while it should indeed not be working.
But I have something more stranger again, I got an other website. Same framework (that means same folder/file structure), same css file, same way of including the file. And with this one using the second method, the file is found in localhost and in server too...while it shouldn't be working with none of them.
I hope you have any idea cause I'm lost at this point. Thanks.
.wrapper-accueil .scroll:before {
content: "";
display: block;
width: 30px;
height: 30px;
background: url("../../assets/img/picto/arrow-down.svg") no-repeat center center;
background-size: contain;
}
May be you have a folder containing picto has on another folder
I'm not sure I get 100% what your problem is, but it seems that you load your css with relative paths from two different starting points:
Loaded with link:
www.example.com/path/to/your/application/style/index.css
=> this loads the asset from:
www.example.com/path/to/your/application/assets/img/picto/arrow-down.svg
Included in site:
www.example.com/path/to/your/application/site.php
=> this loads the asset from:
www.example.com/path/to/your/assets/img/picto/arrow-down.svg
^^^
note the missing path due to "../" in your svg path
Maybe this is the answer to your problem, feel free to clarify if I didn't get you correctly! Please also check the developer console, especially the "Network" tab in Chrome and see what exactly is requested and double check the paths there.

html/php file + css inlining issues

This is my php file, index.php
<html>
<div id='hello'>Hello, <?php $name?>! How are you?</div>
</html>
This is my css file, index.css
<style>
#hello {
font-size: 36px;
color: red;
border: 1px solid red;
}
</style>
I am trying to use the library https://github.com/tijsverkoyen/CssToInlineStyles to convert my index.php file to inline css. The problem is, it converts the closing php tag '?>' to '?&gt' for the closing tag. I know the library is targeting HTML and my file is a .php, but are there a way to stop the '>' tag from being converted to it's respective symbol '&gt'? If so, how?
The index.css should contain only:
#hello {
font-size: 36px;
color: red;
border: 1px solid red;
}
The <style> is a HTML tag and it should not come in a .css file. If you have them inside your .css file, the whole file will not work.
For the what you posted, the short answer is no. At least not without tweaking the library (as you pointed out, it is intended for HTML files).
If you really (really) need to do the "conversion" dynamically (as in "each time the page is requested") you can do that on the client side by manipulating the DOM with some JavaScript. (see here).
If you need the conversion to be done only once and then leave the output file as a server resource you could use template pre-processing.
I'm not sure of why you want to convert to inline css, perhaps if you explain a bit more we could point you in the right direction.
G00d 1uck.
[UPDATE] So the conversion should be dynamic. A way to go is (instead of using a PHP file that contains HTML code with embedded echoed PHP values) to put all html + PHP 'echoed' into a string variable and then inject the result as a stream (or as an actual temp file) to the converter, wait for the output and send it by email.
No, it is (as it should) escaping those characters for you. Your css files should never contain html.
Remove the <style></style> tags and it should work. You only need those if you're putting css into your html.

How can I use PHP code in a CSS file

I want to find an image source from a MySQL database and assign it to a css style. I just changed the .css extension to .php.
It does work with XAMPP and runs everything I want, but when I uploaded my code in cpanel it didn't work correctly.
I used this code in the css file:
Top of page:
<?php include '../Connections/Base.php'; ?>
<?php header("Content-type: text/css; charset: UTF-8"); ?>
Some styles:
.box {
overflow: hidden;
display:block;
border:4px solid #171717;
position:absolute;
cursor: pointer;
float:left;
display: inline-block;
zoom: 1;
background:url(<?php
$query = "SELECT imape_path FROM MyTable WHERE number='5' LIMIT 1";
//echo $query;
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
echo $row['imape_path'];
}
}
?>) no-repeat;
}
How can I fix this problem?
Personally, I do not think this is the right problem to address.
The whole point in separating markup and styles is to simplify things. I see very little value in separating it so rigidly you have to mix css, php and sql instead (you just moved the same problem elsewhere).
My suggestion is to configure .box's background using inline css in the html page itself and inject the url as any other value:
<div class="box" style="background: url('<?php ... ?>')">...</div>
You could try keeping the .css extension on the file with PHP code, and setting a rule in .htaccess to parse the file as PHP (source).
<FilesMatch "^.*?style.*?$">
SetHandler php5-script
</FilesMatch>

How to Change CSS Dynamically

I need my administrator to be able to change/update the banner of my site.
This is the banner code
<div class="containertop">This depends on the background of the div</div>
and this is the CSS for that
.containertop
{
width:1000px;
height:300px;
**background:url(../images/1.png) no-repeat center;**
margin: 0 auto;
margin-top: 40px;
}
What I would like to happen is the same as a Facebook cover photo.
When a new banner is uploaded, the CSS will be updated(something like that).
But of course, the new banner must be fetched from the database.
So I am thinking that the CSS would become like this:
Fetch the saved banner source and then:
background:url(<?php echo $row['image']; ?>);
but can I do the PHP connection to database (include 'dbname.php') inside a CSS txt?
There's nothing preventing you to serve a css generated by PHP. That's even easy.
Simply start your php file like this :
<?php
header("Content-Type: text/css");
I agree with Ben. If you make a little embedded css section in your page, you could put the .containerTop css code there. Then, put your code in the page.
So, in your actual web page, put this:
<style type="text/css">
.containertop{
width:1000px;
height:300px;
background:url(<?php echo $row['image']; ?>);
margin: 0 auto;
margin-top: 40px;
}
</style>
Of course, your background url will not update until it is reloaded. If you decide to do it this way, don't forget to take the .containerTop definition out of your existing css.
Having said all that, I really like dystroy's answer. Very nice. I never thought of doing that.
You can set containertop background while loading php file.
<?php
echo "<style>.containertop{ background:url(../images/".$row['image'].") no-repeat center;}</style>"
?>
This will set the background fetched from db.
Well, You can use jQuery to change/overwrite the CSS file.
Example -
$('.containertop').css('backgroud','url(images/change.jpg) repeat');
or
$('.containertop').css('backgroud','url(<?php echo $images_url ?>) repeat');

php css-less dynamically changeable css designed websites

I am going to start on a website whose requirement is to change the color scheme after every 2 weeks.
I am looking for a dynamic solution to change colours and somewhat structure of a website using css & php.
One solution which i can see is using dynamic css method for example
<?php
header("content-type: text/css");
$mencolour = "#ff0000";
echo 'h1 {color:$menucolor}
?>
Other solution is using some php classes to do the same task.
such as one is available on phpclasses website.
http://www.phpclasses.org/package/6482-PHP-Parse-and-process-Leaner-CSS-files.html
Is there any other better way of doing this? if any one has used above two methods, what could be drawbacks of using them.
Need some expert opinions :)
Sass is a popular CSS pre-processor that, among other things, lets you use variables in CSS, for things like your color scheme. You'd compile the CSS when you change it, so no need for the overhead of running a PHP script each time it loads. (Yeah, you could write your own cache system for that in PHP, but no need to redo others' hard work ;D)
$menu-color: #123456;
#menu { color: $menu-color; }
You can use a body class to change the theme:
/* Base style */
h1 { color: grey; }
.spring h1 { color: green; }
.summer h1 { color: yellow; }
.fall h1 { color: orange; }
.winter h1 { color: blue; }
To change the theme, just add the class on the body:
<body class="fall">
<h1>The leaves are falling!</h1>
</body>
Given that this is on a 2-week schedule, firing off a dynamically generated css file is overkill. It would be far easier to serve up a static .css file, which can be generated by PHP. That way you don't have to mess with outputtting cache headers and whatnot - the file will be cached the way any other static file would.
Use cron a similar timed-job tool to rebuild the .css file whenever you need those color changes to occur.
The PHP method, by default, would cause the clients to re-query the server for changes on every hit. That's a waste of bandwidth and cpu time just to change a few values once every 14 days.

Categories