Reputation: 154695
I have an Apache/PHP based server on which I've made Apache execute js
, html
and css
files as PHP via the following line in /etc/mime.types
:
application/x-httpd-php phtml pht php js html css
We did this because even though any files we save as .html
/.js
/.css
are almost entirely non-PHP, we need to do a bit of templating in them (for example, changing the domain of some URLs depending upon whether we are on the live or testing server).
The trouble is, this method of making Apache treat those files as PHP causes them to be returned with the wrong MIME type, which at the very least breaks css
files in Chromium and probably has nasty effects in other browsers too.
Is there a way I can tell Apache to execute these files as PHP but still output them with the correct MIME type for their file extension? I don't want to have to manually paste
<?php
header("Content-type: text/css");
?>
at the top of all of our .css
files.
Upvotes: 2
Views: 5232
Reputation: 154695
It seems worth me noting that the only reason I ever ended up needing to ask this question was the wrong-headed approach I'd taken to having .js
and .css
files executed by PHP.
Don't modify your mime.types
file to achieve this. Instead, in your Apache config (or in a .htaccess
file), use invocations like this:
<Files *.js>
ForceType application/x-httpd-php
Header set Content-Type "application/javascript"
</Files>
<Files *.css>
ForceType application/x-httpd-php
Header set Content-Type "text/css"
</Files>
Upvotes: 3
Reputation: 449425
We did this because even though any files we save as .html/.js/.css are almost entirely non-PHP, we need to do a bit of templating in them
Why not do the dynamic parts in the main document then, where you are dynamic anyway? Running all the resources through the PHP interpreter is such a waste.
For JavaScript:
<script>
domain = "<? echo $domain; ?>"; <----- dynamic bits here
</script>
<script src="xyz.js"></script> <----- you can use them in xyz.js
For CSS:
<link rel="stylesheet" href="stylesheet.css">
<style type="text/css">
/* insert dynamic CSS here, overriding parts from the static style sheet */
.my_div { color: <? echo $color; ?> }
</style>
Upvotes: 2
Reputation: 167172
You can do it in two ways:
Create a .htaccess
file.
Now inside this file, make all the PHP files to be read as either .js
or .css
. Ideally, you will be having files like: style.css.php
, scripts.js.php
and are executed by Apache but the user will be getting the URL as style.css
, scripts.js
, etc.
Using Mime types.
As you already said, by using the following, you can make these execute in the PHP.
application/x-httpd-php phtml pht php js html css
Or another way is this:
<FilesMatch "^.*?css*?$">
SetHandler php5-script
</FilesMatch>
Upvotes: 0