-1

I wish to run PHP within a css file. The reason for this is that I want to dynamically set the URL of a background image based upon whether the site is in development or production. i.e

<?php Header ("Content-type: text/css; charset=utf-8"); 

$baseUrl = $this->basePath();

if (defined('RUNNING_FROM_ROOT'))
{
    $baseUrl .= '/public';
}

?>

.readersSlidersOne {

    background: url("<?php echo $baseUrl ?>/Images/backGroundImages/side_wallet.png") scroll 0 0 transparent ;
}

the above if clause basically determines whether a full BASE URL SHOULD be used or just the /public

i am aware from this answer that the solution is to create a css file with a php ending- and to then place the code below at the top of the file:

Header ("Content-type: text/css; charset=utf-8");

i did try this and it does indeed create a CSS file with PHP tags (css.php).

However once I place actually php code within the file it stops working.

i.e

$baseUrl = $this->basePath();
Community
  • 1
  • 1
theSeeker
  • 297
  • 4
  • 12
  • 5
    This seems overly complex when you could just fix the development server to have the same base path as production. – ceejayoz Jan 06 '16 at 14:32
  • You can use a `AddHandler` directive in htaccess and make the PHP parser parse the CSS file, but you shouldn't, what you should do is find some other way to do this, and keep PHP out of your .css files – adeneo Jan 06 '16 at 14:32
  • 1
    Or just **compiling the CSS file once** when deploying to production. – deceze Jan 06 '16 at 14:33
  • 1
    _“However once I place actually php code within the file it stops working”_ – that’s most likely because your code produces errors – so go check what the actual output of the script is. – CBroe Jan 06 '16 at 14:33
  • its a zend 2 framework site. so, i am not sure this is possible-hense my need to find a solution. not-with-standing this current problem. it's still a good idea to use the dynamic power of PHP within a css file – theSeeker Jan 06 '16 at 14:34
  • 3
    It's not, really. CSS files should be static and cacheable. Any page-specific alterations should be done in a ` – deceze Jan 06 '16 at 14:35
  • Well for one thing, you're expecting context to exist in your PHP file which (so far as I can tell) doesn't exist. `$this->` isn't set, and `RUNNING_FROM_ROOT` isn't defined anywhere. – samlev Jan 06 '16 at 14:36
  • 1
    "its a zend 2 framework site. so, i am not sure this is possible" It's definitely possible to get a ZF2 site running on the same URLs in development and production. "it's still a good idea to use the dynamic power of PHP within a css file" No, it's not. – ceejayoz Jan 06 '16 at 14:43
  • yes. i totally accept that my approach was wrong-but why did i have to be punished for trying out something new- why do people feel that they have the right to stifle debate on possible new approaches! – theSeeker Jan 06 '16 at 15:18

5 Answers5

4

what I normally do in this case, I add that specific css in on top of required page and change the value dynamically. this is if the css is very page specific

<?php
$path = 'http://www.example.com/image.jpg';
?>
<style>
.className{
 background: url(<?php echo $path; ?>);
}
</style>

OR if you want to put it in header include file, basically in one place for all files, add if else statement and add a $page variable on top of your page

<?php 
// define this before including the file contaiting $path
$page = 'index';   ?>
<?php
if($page == 'index'){
  $path = 'http://www.example.com/image01.jpg';
}elseif($page == 'contactus'){
  $path = 'http://www.example.com/image02.jpg';
}
?>
Daniel PurPur
  • 519
  • 3
  • 13
2

CSS files should be static and cacheable. You should not be dynamically generating CSS files through PHP.

  • If the change needs to be made once between production and staging environments, then only do it once during your deployment phase (when uploading to the respective environment). Either use some sort of build/deploy script, a CSS pre-processor, or whatever else fits best. There's no need to do this on every single request through PHP.
  • If you want to customise the look of a page based on dynamic values, place a <style> section in your HTML page which you're generating through PHP anyway (or apply style=".." attributes to affected elements directly); you can dynamically manipulate that through PHP all you want.
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Plus One - definitely best practice to load different style sheets or inline styles – Lionel Ritchie the Manatee Jan 06 '16 at 14:43
  • consider: theres a static stylesheet, but also user has specific ui settings that require lots of altered rules.. it would be better to create a second dynamic stylesheet than to junk up the source with – I wrestled a bear once. Jan 06 '16 at 14:54
  • @Pamblam Consider: CDN. If you're only talking about client-side caching, then yes, "static enough" is good enough. But this is a roadblock to really scaling up and employing *server side caching*. I'll assume there are only a very finite, defined number of things a user can configure; in that case using `class` attributes in the HTML and static CSS rules which apply to those classes is a lot preferable to dynamically generating stylesheets. – deceze Jan 06 '16 at 14:59
  • @Pamblam I'm not saying there are never situations where generating stylesheets makes sense; but certainly not in the case of the OP, and it should certainly not be your first instinct. – deceze Jan 06 '16 at 15:01
  • my first instinct is usually to assume the op knows what they're doing and just answer their question.. maybe that's not the best approach – I wrestled a bear once. Jan 06 '16 at 15:03
  • @Pamblam If the OP knew what they were doing they wouldn't be asking here. ;-) – deceze Jan 06 '16 at 15:04
  • yes. i totally accept that my approach was wrong-but why did i have to be punished for trying out something new- why do people feel that they have the right to stifle debate on possible new approaches! – theSeeker Jan 06 '16 at 15:18
  • @theSeeker [Read this first.](http://meta.stackoverflow.com/a/253230/476) – Then: your actual problem description is "stops working", which is a terrible "question". We're basically just ignoring this "exact" problem description because your overall approach is wrong to begin with. – deceze Jan 06 '16 at 15:22
1

unless this file is included somewhere inside a class definition, $this-> is out of context. You will have to come up with another way to get the correct path.

Use:

$Livedomain = "mysite.com";
$Devdomain = "localhost/mydomain";
$baseUrl = strpos($Livedomain, $_SERVER['PHP_SELF']) === false ? $Devdomain : $Livedomain;

Also, you can send caching headers to prevent excessive requests and keep your page loading quickly..

$seconds_to_cache = (60 * 60 * 24 * 90); // 3 months-ish
$ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
header("Expires: $ts");
header("Pragma: cache");
header("Cache-Control: max-age=$seconds_to_cache");
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
0

You're on the right track - to run PHP code within a CSS file, you would make a *.php file and send a CSS header through it, like so:

myStyles.php

make sure you put no PHP code or whitespace before the Header()

<?php Header("Content-type: text/css; charset=utf-8"); ?>
<?php

    $wht = '#ffffff';   
    $blk = '#000000';

    // This line probably isn't working because $this is not defined
    $baseUrl = $this->basePath();

?>

div#id {
    background-color: <?php echo $blk; ?>;
    color: <?php echo $wht; ?>;
    background-image: url('<? echo $baseUrl; ?>/images/myimage.jpg');
}

With that being said, have you tried toying around with preprocessors like LESS or SASS, which can be used to do what i assume is a vast majority of what you're trying to accomplish?

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
  • 3
    I'm just interested because I've rarely seen this approach. Isn't this a bad practice to mix CSS and PHP when you can use LESS or SASS (which you also mentioned) as preprocessors? – Philip Feldmann Jan 06 '16 at 14:37
  • It's not typically good practice to send css headers from a PHP file like that, no, but there can always be a reason for anything. Most folks would likely use LESS OR SASS to create different config files as dependencies for their CSS and then load the proper config using a PHP script. – Lionel Ritchie the Manatee Jan 06 '16 at 14:40
  • not bad practice.. you can even configure apache to process php from `.css` files. – I wrestled a bear once. Jan 06 '16 at 14:40
  • 1
    @Pamblam But that's bad practice. CSS files should be static and cacheable. Making them dynamic generally means a lot more work for the server, a lot more bandwidth usage, and a slower site. – ceejayoz Jan 06 '16 at 14:42
  • you know how you fix that? by sending caching headers.. dynamic css is dynamic css, whether you're using sass or php, if the css has changed it's going to have to be reloaded. at least with PHP you can control caching with `header()` – I wrestled a bear once. Jan 06 '16 at 14:45
  • SASS is not dynamic - it's a preprocessor. `*.scss` or LESS using `*.less` files are pre-processed into minified CSS, which is then loaded to the DOM. – Lionel Ritchie the Manatee Jan 06 '16 at 14:48
  • ok fine, but still, you can send caching headers with PHP and achieve the same effect. – I wrestled a bear once. Jan 06 '16 at 14:51
  • Check out this post: http://programmers.stackexchange.com/questions/118052/why-dont-we-use-dynamic-server-side-generated-css – Lionel Ritchie the Manatee Jan 06 '16 at 14:58
  • that post is like re-reading the conversation we just had. it literally covers everything we were just talking about except an answer on that page points out that less is in fact dynamic (which i didn't know, i've not used either less or sass).. but like i said, and others on your linked page have said, the problem can be overcome by sending the appropriate caching headers when a better option is not feasible. – I wrestled a bear once. Jan 06 '16 at 15:14
  • yes. i totally accept that my approach was wrong-but why did i have to be punished for trying out something new- why do people feel that they have the right to stifle debate on possible new approaches! – theSeeker Jan 06 '16 at 15:21
0

This is just an idea.... isn´t easier for youto inject only the background image in the html? Ex:

// Somewhere in your html oh Head
<?php
 $image = 'http://www.tld.com/yourImage.jpg';
?>

<div id="myId" style="background-image:<? echo $image; ?>"></div>

Then you don´t need to do nothing in the essence of your CSS and this will save you loads of time!!!! :)

Nuno Bentes
  • 1,475
  • 13
  • 26