use PHP to create an external dynamically generated CSS file.


/ Published in: PHP
Save to your folder(s)

One other thing to note, is that the php generated css file can make use of query parameters, for instance:

<link rel="stylesheet" href="base.css.php?type=alternate" type="text/css" >

in your PHP file you can use the variable:

if ($_GET['type'] == 'alternate'){
// set some options etc. ....
}


Copy this code and paste it in your HTML
  1. -- This is a very easy way to create a dynamically generated CSS file in PHP
  2. --
  3. -- The important parts of the code below:
  4. -- 1. note that the PHP generated CSS file must start out with
  5. -- header('Content-type: text/css');
  6. --
  7. -- 2. The file name should end in .php not .css , since this is a PHP file.
  8. --
  9. -- Why this works: when the CSS file is requested by the remote server, the
  10. -- server sees the .php extension and preprocesses it before sending it to
  11. -- the client browser. Since the PHP file sets the Content-type as text/css
  12. -- the client browser treats it like a CSS file.
  13. --
  14. -- Code written by dbug13(Jamie Allison)
  15.  
  16. ----- Begin Dynamic CSS file: base.css.php -----
  17. <?php
  18. header('Content-type: text/css');
  19.  
  20. // Try changing the variables below, and refresh your html file.
  21. $bg_color = "purple";
  22. $base_font="Verdana,Arial,sans";
  23. ?>
  24. body{
  25. font-family: <?php echo $base_font; ?>;
  26. background-color: <?php echo $bg_color; ?>;
  27.  
  28. }
  29. ?>
  30. ----- End Dynamic CSS file
  31.  
  32. ----- Begin HTML file that uses above CSS file: index.html -----
  33. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  34. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  35.  
  36. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  37. <head>
  38. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  39. <!-- Include the dynamic CSS file -->
  40. <link rel="stylesheet" href="base.css.php" type="text/css" media="screen" title="no title" charset="utf-8">
  41. <title>untitled</title>
  42.  
  43. </head>
  44.  
  45. <body>
  46.  
  47. <h1>Hello World</h1>
  48.  
  49. </body>
  50. </html>
  51. ----- End HTML file -----

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.