The Problem

Have you ever tried to write code like this?

external.js

function test_javascript()
{
   console.log( 'Currently at page: <?php echo $_SERVER['SCRIPT_URI'] ?>' );
}

index.php

<script src="external.js"></script>

Most of the time, you will find that the external.js file will have an error because it cannot make sense of the PHP snippet.  The following is how you can make that code work.

Update the server rules

Within any folder of your server structure, you can place a “.htaccess’ file.  This file tells the server a number of things about permissions, caching, permissions, etc.  Specifically, this is where rules on which file extensions are run through the server language processes before those files are served to the client.

In this case, we want to run ‘.js’ files through the PHP parser before the ‘.js’ file is served to the client.  To do that, we add this to the ‘.htaccess’ file:

Options +ExecCGI
AddHandler x-httpd-php .js

If you are a GoDaddy client, they have more detail here:
http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions?locale=en&ci=46061

Change the Extension

When you make the change in the ‘.htaccess’ file, you are telling the server to run all external Javascripts through the PHP parser.  Chances are that you have external files that do not contain PHP, so the server will unnecessarily be running processes on files; thus, your pages are served up a bit more slowly.

This is where I suggest a special extension for external Javascript files that respect PHP.  In this case, I have changed ‘external.js’ to ‘external.php.js’.  And when I do this, I have to change the rule in the ‘.htaccess’ file too:

Options +ExecCGI
AddHandler x-httpd-php .php.js

Trick the Browser

When the browser sees a ‘.php.js’ file, it does not know what to make of it – so you have to tell it that it really is a Javascript file.  At the top of the external.php.js file, add the following:

<?php
header('Content-Type: application/javascript');
?>

That’s all there is too it.