Why don't people make .php
files for their CSS
and JavaScript
files?
Adding <?php header("Content-type: text/javascript; charset: UTF-8"); ?>
to the file makes it readable by browsers, and you can do the same thing to css files by setting the Content-type
property to text/css
.
It lets you use all the variables of PHP and methods into the other languages. Letting you, as an example, change the theme main colors depending on user preferences in css, or preloading data that your javascript can use on document load.
Are there bad sides of using this technique?
PHP is a server side language and CSS and PHP do not interact with each other. Though you can output CSS to interact with your HTML, using PHP. Using CSS with PHP is even more simple that you might think. Similar to echoing out a text string in PHP, CSS is echoed out the same way.
You can resolve this problem by: Using the correct file path to the CSS file. So if the CSS file is in a different folder from the HTML path, you need to identify the path name and add it to the link href value.
PHP gathers and processes the information that it needs to create the web page in HTML and JavaScript before it sends the finished web page to the browser. So, when we develop web pages, we can have a combination of HTML, JavaScript, CSS and PHP in our pages.
Answer: PHP allows dynamic web page generation, which is not possible by using just HTML. Thus by using PHP script along with HTML in a PHP file, the web developers can generate dynamic web pages. The use of PHP also allows access to various databases.
People do it more often than you think. You just don't get to see it, because usually this technique is used in combination with URL rewriting, which means the browser can't tell the difference between a statically-served .css file and a dynamic stylesheet generated by a PHP script.
However, there are a few strong reasons not to do it:
And there are a few alternatives that are easier to set up:
If you want to use PHP to generate CSS dynamically after all:
<link rel="stylesheet" type="text/css" href="http://example.com/stylesheet.css?dummy=121748283923">
) and change it whenever the script changes: browsers will interpret this as a different URL and skip the cached version.Content-Type
headers.Some do, the better thing to do is generate your JS/CSS scripts in PHP and cache them to a file.
If you serve all of your CSS/JS files using PHP, then you have to invoke PHP more which incurs more overhead (cpu and memory) which is unnecessary when serving static files. Better to just let the web server (Apache/nginx/lighttpd/iis etc) do their job and serve those files for you without the need for PHP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With