How can I use PHP code in a CSS file - php

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>

Related

How to call the percentage of a number in a PHP variable to HTML/CSS?

I am trying to pass the percentage in HTML/CSS but I can not succeed.
I am trying:
<?php
$myPercentage = 100;
?>
I am trying to pass the variable in HTML/CSS. I want my progress bar to increase/decrease according to the PHP value.
<style>
.bar-4 {width:70%; height: 18px; background-color: red}
/* Here is the problem, the above progress bar 4 is working and its width increases to 70% but below code is not working. */
.bar-5 {width: <?php echo $myPercentage;?>%; height: 18px; background-color: #4CAF50;}
</style>
Your idea or suggestions would be welcome.
Thank You.
You question lacks some important data, but here are the general guidelines that will make it work:
To have a dynamic variable in the CSS block, you need to be echo the relevant part, or include it in the PHP file (and not on a separate CSS file)
The value given to the variable must come before the CSS block.
So for example, your PHP file should have something like:
<?php
$myPercentage = 100;
?>
<style>
.bar-5 {width: <?php echo $myPercentage;?>%;}
</style>
For cleaner code, the rest of .bar-5 CSS is better to stay in your CSS file, and only the dynamic values should be printed as inline CSS.

Embedding PHP code in a CSS file

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.

How to get variable`s value of CSS from database in yii?

I am working on app in which i need to get value of the color attribute from database(Hex value) to make it custom.
I searched on internet i found a solution that i can use css file as php file including this line in css file
<?php
header("Content-type: text/css;");
$bannerColor="#b229b6";
?>
when i select banner color in above code then i show it in css selector like this
#banner {
background-color:<?php echo $bannerColor; ?>;
width: 100%;
height: 436px;
}
it works fine. But when i try to write query in php code(at the top of this php file), the css gets out of order on the main page where i have used this file. When i remove query code it works fine as earlier.
My question is that
1. Can i use $banner= Color::model()->findAll(); in this file? If Yes then what i am doing wrong here?
2. If it can not be used then how to accomplish this task? thanks for your help.
Yourcss.php don't have YII context within, you can:
In your main (layout) file, get your value from database and put into a cookie:
$banner= Color::model()->findAll();
$_COOKIE['bgColor'] = get your value from $banner
In yourcss.php file you should get this value from cookie as:
<style>
#banner {
background-color: <?php echo $_COOKIE['bgColor']; ?>;
width: 100%;
height: 436px;
}
</style>

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');

How to optimize html, css runtime on server for better loading time?

Many times I have read on many question's answers that we don't need to remove white-space and comments from html, css and js files to reduce file size manually We can do this automatically on server.
1) Is it like in my dreamweaver it will be like this
/*Some Comment*/
.footer li h3 {
margin: 0 0 6px;
font-weight: bold;
display: inline;
color: #e92e2e; }
/*Some comment*/
.footer li h3 a {
font-weight: normal;
font-size: 1em;
color: #e92e2e; }
On server it will be this ?
.footer li h3{margin:0 0 6px;font-weight:bold;display:inline;color:#e92e2e}.footer li h3 a{font-weight:normal;font-size:1em;color:#e92e2e}
I can do this by hand or using this tool http://www.refresh-sf.com/yui/
2) How to do this on Lamp server?
3) On server do we just remove white space and comments?
You need a minifying tool. Try googling yuicompressor and go through its docs. You will need to create an Ant script to automate this.
If you want to remove white space on runtime, you could use PHP to serve the CSS:
<?php
$lines = file('yourCssFile.css');
$content = '';
foreach ($lines as $line_num => $line) {
$content .= trim($line);
}
header("Content-type: text/plain"); // <-- change accordingly
echo $content;
Then you would just link to the php file in your html instead. You can do similarly for html, js and css. Of course, the effect that this will have on the overall speed will be minimal. Using gzip compression will be far better.
If that's how your CSS file looks in Dreamweaver, it will display the same for anyone else (even if they open it in Notepad).
In order to reduce file sizes you should minify your code. There are several tools/compilers/sites that will do it for you. Below are three well-known sites/tools for compression.
Minify CSS
Google Minify (HTML/CSS/JS)
Yahoo UI Compressor (HTML/CSS/JS)
Something else you may want to take into consideration is caching your sites. Hope this helps!

Categories