Tutorial Use PHP inside JavaScript

by in , 0

This has only really been tested on Media Temple (gs) servers.

In the folder with the JavaScript, the .htaccess file should include:

<FilesMatch "^.*?api.*?$">
SetHandler php5-script
</FilesMatch>

In that above example, any file that includes the string "api" will be processed as PHP. Feel free to alter that RegEx.

Then in the JavaScript file itself, set the ContentType back to JavaScript:

<?php
	// Sets the proper content type for javascript
	header("Content-type: application/javascript");
?>

That will ensure browsers reading the file will interpret it as JavaScript. Now you can use <php ... ?> tags in the JavaScript file to do whatever PHP stuff you need to do.

Leave a Reply