Execute PHP Code Inside HTML/JavaScript Files Using .htaccess

Execute PHP Code Inside HTML/JavaScript Files Using .htaccess

Most of developers always have a common problem, how we can add php code inside an external javascript files. The most
Common way is define global javascript variables on .php file and access them in your javascript files. This has drawback
that we have to define all variables global to access them to javascript files.


var temp = “<?php echo $phpTemp ?>”;



We have another way to do this, i.e. just change mime type of .js file to application/x-httpd-php. Now server parses all

Files end in .js. This will take a little extra server burden. And you can use this same technique for any extension you

want .html, .htm etc.


To understand this let check how APACHE WEB SERVER resolve .PHP requests:


1) HTTP requests http://www.ost.agency/test.php

2) Web server extract mime type of the file extension

3) Default mime type of .php is application/x-httpd-php

4) PHP engine is configured to run documents with mime type application/x-httpd-php

5) PHP engine parses it and passes the results to Server.

6) Server sends the results to client.


Now to change mime type we only need to add few lines in our .htaccess file and that is:


AddType application/x-httpd-php .htm .html .js

AddHandler x-httpd-php5 .htm .html .js

<FilesMatch “\.(htm|html|.js|php)$”>

SetHandler application/x-httpd-php


Happy Coding 🙂

Latest Blogs