ih ave read about the technique to allow dynamic HTML stylesheets using PHP's preprocessor, however I was windering how safe this tecnique is, and if for any reason it is discouraged.
For example, instead of using typical:
<link rel="stylesheet" type="text/css" href="http:mysite.com/style.css/>
I could use:
<link rel="stylesheet" type="text/css" href="http:mysite.com/style.php/>
What do you think?
It's perfectly fine.
I'd suggest setting the following header in the PHP though:
Header("Content-Type: text/css");
If you can use .htaccess files you can set it up to parse *.css files as PHP using:
AddHandler application/x-httpd-php .css
Then you can use PHP directly within your *.css files.
Be sure to also set the header type to text/css as the others have mentioned as well:
header('Content-type: text/css');
It's only as safe as the code that you put into style.php.
Yes, you can use PHP to generate your stylesheet. Make sure to declare the output properly as CSS by sending an appropriate Content-Type value specifying both the media type and the character encoding.
But note that it costs additional time and resources to generate the stylesheet with every request. So you should add some kind of caching mechanism (static files and HTTP caching) to reduce server load and even unnecessary requests.
As others have mentioned, PHP can be used to output any kind of text. So it's not a problem to output dynamic CSS (or even dynamic JavaScript). Be aware though that you're increasing your server load by doing this. The server will have to fire up the PHP engine to serve what would otherwise be a simple static .css file.
You can render any kind of Text Output with PHP (and other stuff) including CSS, just make sure the right header is given header('Content-Type: text/css; charset=iso-8859-1'); (or any other charset).
But to be honest I can't think of an Situation were it would be necessary to use a dynamic stylesheet in that manner.
Related
I have color.php and index.php:
color.php:
header("Content-type: text/css", true);
$color = "#ff0000";
echo"#div{$color}";
index.php
<link rel='stylesheet' type='text/css' href='color.php' />
<?php
echo"$color"; // want to use the stylesheet color php here
?>
but $color is empty.
any ideas how can I use the color.php $color value?
thank you friends!
The browser makes an HTTP request to fetch the HTML document.
Then the link element causes the browser (unless the results are already in its cache) to make another HTTP request to fetch the stylesheet.
Each request (assuming both URLs are handled by PHP) runs a different PHP program which is not connected to the other (except, possibly, through session data).
The two different programs do not share variables between themselves.
Data could be shared between them (e.g. via a session or a database) but in that case, the stylesheet would load second so you would be trying to read the data (while generating the HTML document) before it had been stored.
If you want to write library files in PHP, then use a mechanism such as include to load them. You can't do it by going through the browser.
Does anyone know how to achieve something like TypeKit when combining multiple CSS request? Maybe I'am not aware of that but when you list some fonts the site would generate (maybe dynamic) CSS like 567,568,569.css lo load the font-file. I thought of it as dynamic as it would change if you use other combination (in this case font ID).
I use the technique described by Carpetsmoker, but I didn't like the fact that the PHP script is invoked every time. On Apache, you can set the following rewrite rule (in .htaccess):
RewriteCond %{REQUEST_URI} ^/css/cache
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^css/cache/(.*)$ /css/csscacher.php?files=$1 [L]
So say a request comes in for /css/cache/file1.css-file2.css, Apache will test for its existence. If it doesn't exist, the request will be forwarded to the csscacher.php script with the filename passed as the value of the "files" param. csscacher.php will load and combine the multiple files, send the result to the browser, but also write the result to /css/cache/file1.css-file2.css. All subsequent requests will be served as a static file.
To clear the cache, you'd just delete everything in the /css/cache folder. csscacher.php will recreate them from the source files as requests come in. More detail here.
You could also just use
#import url('reset.css');
at the top of your main css fiel to import other css files on the fly.
Have a look at the Google minify project. It offers a good solution to combine and also compress your JavaScript or CSS files. It is a PHP library that you can set up on your webserver with a script that takes a list of JS or CSS files and outputs a concatenated version. It also caches the result.
The implementation could be separated into three steps. Firstly, define a control wraps all the reference JS files.
Secondly, during the rendering of that control, using any kind of algorithm (e.g. encoding / encrypting) for all file paths to a string, and generate the script tag with a src which points to a certain handler with that generated as querystring.
e.g. Image we have two files: a.js and b.js, we have a control wraps them and generates the script tag like:
<script type='text/javascript' src='/js.php?include=encodeab'></script>
Thirdly, when client side displays the html page and sends request for that script tag, a certain server side handler (js.php in above case) will decode / decrypt that querystring to a list of included files, then read content of them, combile together and output to stream.
Hope this helps.
Be wary using dynamic js or css files as you may accidentally force the user to download them on each page (instead of using browser caching).
You can include multiple javascript/php files into one file, then give it a header of type javascript:
header("Content-type: text/javascript");
include('javascript1.php');
include('javascript2.js');
The same holds true for CSS.
Resources:
http://www.javascriptkit.com/javatutors/externalphp.shtml
http://www.webmasterworld.com/php/4239826.htm
You can use something along the lines of:
<?php
header('Content-Type: text/css');
if (isset($_GET['files']))
{
$files = explode(',', $_GET['files']);
foreach ($files as $file)
{
# BEWARE!
# What happens if the file is ../../../../../../../../etc/passwd?
$file = str_replace('..', '', ltrim($file, '/'));
include($file);
}
}
?>
test.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.php?files=style1.css,style2.css" />
</head>
<body>
<h1>This should be red</h1>
<p>red border</p>
</body>
</html>
style1.css
p { border: 1px solid red; }
style2.css
h1 { color: red; }
This is a simple example, you can easily expand it to allow javascript files. Another good optimisation would be setting the Last modified headers based on the mtime of the .css files (use stat()) ... But the general idea should be clear.
BEWARE, to be honest, I'm not sure if the escaping/parsing of the $_GET['files'] is enough ... Please research this topic to be sure, this can a very dangerous security problem :-)
Hope this is enough to get you in the right direction.
You can do something close by calling a dynamic JS file:
start with a php file and then in it:
<?php
if(isset($_GET['jsOne'])){
include'example.com/js/one.js'; // points to some .js file
}
if(isset($_GET['jsTwo'])){
include'example.com/js/two.js'; // points to some other .js file
}
if(isset($_GET['jsThree'])){
include'example.com/js/three.js'; // points to yet a another .js file
}
?>
and in the header just have:
<script type="text/javascript" src="js/allScripts.php?jsOne=yes&jsThree=yes"> and so on
Hope this helps.
is there a way to style a php file with css so I can use border,padding, align and teother various
will this work or not if i added to the php or will i need functions for using this
<link rel="stylesheet" type="text/css" href="style.css" />
You cannot and probably will never be able to style a PHP file using css. What you want to style using css is the html content created using PHP and/or javascript! That is because styling takes place on the client machine in order to show things to the user while php gets executed on the server machine in orderf to produce code which will be readable by a browser.
<link rel="stylesheet" type="text/css" href="style.css" /> will work if the file style.css is found at that location (i assume your are using valid css definitions in your file)
You can use css to style HTML files. PHP generates HTML (or not) and you cannot style PHP files.
PHP doesn't know or care about CSS, and neither does it need to.
PHP runs on the server and does whatever it does, which should result in an HTML document.
This HTML document is send to the browser.
Only the browser cares about CSS, and it doesn't care whether an HTML document was just a file on the server's hard disk or whether it was created by PHP or magic fairies.
If the document the browser receives is an HTML document, you can use CSS with it. PHP has absolutely zero influence on this.
You don't style PHP with CSS. What's there to style? It's all just server-side code that generates HTML. You style HTML with CSS, not PHP.
If you are looking for a way to define styles in variables i.e. colour etc and make it easier to generate css try http://lesscss.org/
It's what I use to make css edits faster instead of copying and pasting.
How does one create Dynamic CSS and JavaScript On-The-Fly (using PHP).
This needs to be done as different pages have different set of elements sometimes, so wrapping and sending a large CSS/JS everytime would be overkill.
And why do many sites have link tags like this:
<link rel='stylesheet' type='text/css' href='css/style.css?pg_id=43&post=62'>
How does the CSS come to know the GET parameters?
Since this might involve URL rewriting or using the header function, please supply short examples
So, there's a few different approaches you can take here. First, if you have access to apache's virtualhost files, you can set CSS to be read by a php interpreter. I've never done this and wouldnt exactly recommend it but an example is:
<VirtualHost *:80>
AddType application/x-httpd-php .css
</VirtualHost>
This can also be done in your .htaccess file.
Alternatively, you can make a link like
<link rel='stylesheet' type='text/css' href='css/style.php?pg_id=43&post=62'>
and put
<?php header("Content-type: text/css"); ?>
as the first line.
I've never considered Vinicius' technique but I don't doubt that has its own set of advantages and disadvantages too.
PS - sometimes GET variables are uses for caching purposes (or actually to prevent caching by appending the current unix timestamp to the css link with php like
<link href="style.css?<?php echo time()" type="text/css" rel="stylesheet" />
A request to a .css or .js file can be redirected to a PHP script using, for example, an .htaccess (in Apache), so even if the src attribute is "style.css", it's actually a PHP script that is responding to the user.
Your CSS and Javascript files are cached, I would not recommend serving different style sheets / js files unless they're >200KB or so in size.
And yes, you can reference any server-side page with parameters (.php or whatever extension) as long as it returns the correct Content-Type for that file.
Sidenote: Usually if you have parameters and are dynamically serving files in this manner, I believe they will not be cached automatically unless you set it up to do so.
Simple example:
<link rel="stylesheet" type="text/css" href="/css.php?color=wide-red">
<?php
header('Content-Type', 'text/css; charset=utf-8');
$colorScheme = (string)$_GET['color'];
switch ( $colorScheme ) {
case 'wide-red':
$bgColor = 'c0c0c0';
$fgColor = 'ffffff';
$width = '1280px';
break;
case 'normal-gray':
$bgColor = '333333';
$fgColor = 'ffffff';
$width = '960px';
}
break;
}
?>
body {
background:<?php echo $bgColor;?>;
color:<?php echo $fgColor;?>;
width:<?php echo $width;?>;
}
You can use echo, you can use a templating system, you can pull in other css files with file_get_contents, key thing is you need to send the right Content-Type, grab the right parameters and have a default fallback if no parameters are given.
I have about 7 Javascript files now (thanks to various jQuery plugins) and 4-5 CSS files. I'm curious as to what's the best practice for dealing with these including where in the document they should be loaded? YSlow tells me that Javascript files should be--where possible--included at the end. The end of the body? It mentions that the delimeter seems to be whether they write content. All my Javascript files are functions and jQuery code (all done when ready()) so that should be OK.
So should I include one CSS and one Javascript file and have those include the rest? Should I concatenate all my files into one? Should I put Javascript my tags at the very end of my document?
Edit: FWIW yes this is PHP.
I would suggest using PHP Minify, which lets you create a single HTTP request for a group of JS or CSS files. Minify also handles GZipping, Compression, and HTTP Headers for client side caching.
Edit: Minify will also allow you to setup the request so that for different pages you can include different files. For example a core set of JS files along with custom JS code on certain pages or just the core JS files on other pages.
While in development include all the files as you normally would and then when you get closer to switching to production run minify and join all the CSS and JS files into a single HTTP request. It's really easy to setup and get working with.
Also yes, CSS files should be set in the head, and JS files served at the bottom, since JS files can write to your page and can cause massive time-out issues.
Here's how you should include your JS files:
</div> <!-- Closing Footer Div -->
<script type="application/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"></script>
</body>
</html>
Edit: You can also use Cuzillion to see how your page should be set up.
Here's what I do: I use up to two JavaScript files and generally one CSS file for each page. I figure out which JS files will be common across all of my pages (or enough of them so it's close - the file containing jQuery would be a good candidate) and then I concatenate them and minify them using jsmin-php and then I cache the combined file. If there are any JS files left over that are specific to that one page only, I concatenate, minify, and cache them into a single file as well. The first JS file will be called over a number of pages, the second only on that one or maybe a few.
You can use the same concept with CSS if you like with css-min, though I find I usually only use one file for CSS. One thing extra, when I create the cache file, I put in a little PHP code in the beginning of the file to serve it as a GZipped file, which is actually where you'll get most of your savings anyways. You'll also want to set your expiration header so that the user's browser will have a better chance of caching the file as well. I believe you can also enable GZipping through Apache.
For the caching, I check to see if the file creation time is older than the amount of time that I set. If it is, I recreate the cache file and serve it, otherwise I just get the existing cached file.
You haven't explicitly said that you've got access to a server-side solution, but assuming you do, I've always gone with a method involving using PHP to do the following:
jquery.js.php:
<?php
$jquery = ($_GET['r']) ? explode(',', $_GET['r']) : array('core', 'effects', 'browser', 'cookies', 'center', 'shuffle', 'filestyle', 'metadata');
foreach($jquery as $file)
{
echo file_get_contents('jquery.' . $file . '.js');
}
?>
With the snippet above in place, I then call the file just like I normally would:
<script type="text/javascript" src="jquery.js.php"></script>
and then if I'm ever aware of the precise functionality I'm going to need, I just pass in my requirements as a query string (jquery.js.php?r=core,effects). I do the exact same for my CSS requirements if they're ever as branched.
I would not recommend using a javascript based solution (like PHP Minify) to include your css as your page will become unusable if the visitor has javascript disabled.
The idea of minifying and combining the files is great.
I do something similar on my sites but to ease development I suggest some code which looks like this:
if (evironment == production) {
echo "<style>#import(/Styles/Combined.css);</style>"
} else {
echo "<style>#import(/Styles/File1.css);</style>"
echo "<style>#import(/Styles/File2.css);</style>"
}
This should let you keep your files separate during dev for easy management and use the combined file during deployment for quicker page loads. This assumes you have the ability to combine the files and change variables as part of your deploy process.
Definitely look into including your js at the bottom and the css at the top as per YUI recommendations as keeping the JS low has a tangible affect on the appearance of the rest of the page and feels much faster.
I also tend to copy+paste all of my jquery plugins into a single file: jquery.plugins.js then link to
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">
for the actual jquery library.