I want to control the CSS for a third-party website using PHP. Say I want to change font size of the website which I will take as input from the user. Can I do that?
5 Answers
You could have the entire .css file generated by PHP each time, but that's a bit of a waste of CPU. Instead, why not just take advantage of the cascading nature of css? Have your PHP output a small snippet of CSS into each page to override the font set in the .css file:
<head>
<link rel="stylesheet" href="styles.css" type="text/css">
<style type="text/css">
#some_element {
font-size: <?php echo $user_selected_font_size ?>px;
}
</style>
etc...
That way you don't have to dynamically generate the entire .css each time and it can be cached by the client's browser, and you can still give them selectable font-sizes.
3 Comments
You can parse and rewrite the current css file. Probably a better choice will be to load 2 CSS files in your main page, one will be the default one, and the other will be generated by PHP after user add his input. All the second CSS file will have instead are properties that have to be altered (for example font, or font instead of divs, etc).
Another solution will be to store in a DB users input and generate CSS code from that data in your file.php:
print "
<style type=\"text/css\">
body {
color: purple;
background-color: {$color} }
</style>
";
while $color is an local variable created from the DB.
Comments
The preferred way to do this is to use JavaScript to modify the styles of certain elements on the fly. Look into jQuery for that.
Alternatively (and less preferred), you could make your CSS a PHP file (use a .php extension but include it like a .css file) and toss some variables in there.
2 Comments
<link rel="stylesheet" type="text/css" href="style.css.php">?yes, you can create mystyle.php and link it as <link rel="stylesheet" type="text/css" href="[yourdomain]/mystyle.php">
inside mystyle.php you can do usual php stuff like this:
html, body{
font-size: <?php mysql_... ... ?>
}
Furthermore you can add some mod_rewrite features to your .htaccess file in order to give 3-rd party site a possibility to access to your mystyle.php as mystyle.css (but this is of course an optional feature and everything will be ok even without .htaccess)
Comments
You can only do this if the external css is being served in some way by PHP.
I would recommend that the easiest approach might be to override the CSS definitions by either manipulating the DOM with Javascript or (even easier!) including a <style> tag inline within the page that you're rendering with PHP already.