Using Php In .js File?
So I'm trying to use PHP in a .js file, here's what I have so far. .htaccess (any *.api.js will be processed as PHP) SetHandler php54-script
Solution 1:
Create an file with php extension and include it in your website as javascript.
map.api.js
<?php
header("Content-type: application/javascript");
//my php here?>//my javascript here
In your HTML File:
<scripttype="text/javascript"src="map.api.php"></script>
If you wan't to hide the php extension, you can work with mod_rewrite (Apache):
RewriteEngine on
RewriteRule ^map.api.js$ map.api.php
Solution 2:
You don't actually need to set PHP as handler for your .api.js
files. You can use .php
files as scripts too, as long as you preserve your Content-Type
header.
So your file would be something like:
<?php
header("Content-Type: application/javasctipt);
// code...
?>
alert("This is JS");
And in your HTML page you can include it like this:
<scriptsrc="/map.api.php"></script>
This is also useful if you want to manipulate the JS code using PHP before sending it to the client, so you can do something like this:
<scriptsrc="/map.api.php?feature=1"></script>
and in your PHP:
<?php
header("Content-Type: application/javasctipt);
?>
alert("This is JS");
<?php
if ($_GET["feature"] == "1") {
echo "alert('Cool feature imported');";
}
?>
Solution 3:
Take's response is the best practice.
If you really want executing PHP code inside dotJS files.
.htaccess
<FilesMatch "\bapi\b">
SetHandler php54-script
</FilesMatch>
And be sure you allow .htaccess in your Apache config:
<Directory /your/path>
AllowOverride AllOrder deny,allow
Deny fromall
Satisfy all
</Directory>
Post a Comment for "Using Php In .js File?"