How to execute / run PHP code inside JavaScript files?

Static files of JavaScript would survive most applications but sometimes the ability to include PHP code inside JavaScript scripts and generate the content of the script files on the fly by PHP is a better option. How does one do that?

The simplest solution is to just include PHP code inside the <script></script> section of your HTML templates / web pages because chances are, the file extension is .php:

var jsVar = "<?php echo $phpVar ?>";

Even if it’s not ending in .php, such as in .html or .htm, you can configure your server to parse all .html or .htm files for any PHP code, though with a little extra server burden.

Another solution for this is to make your server parse all files ending in .js. Just create a .htaccess if it doesn’t exist in the directory in which you wish to include and run PHP code inside all .js files. Add these lines at the end of .htaccess:

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js

<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php

Now you can add all the PHP code you can inside any JavaScript files with a .js extension, the server will automatically parse and run them when the client side requests the file.

15 thoughts on “How to execute / run PHP code inside JavaScript files?”

  1. Pingback: PHP and JavaScript Variable / Value Transfer / Exchange: How to pass variable values from PHP to JavaScript or JavaScript to PHP?

  2. You could also create a file with a .php extension that returns all the proper headers, and then alias it with mod_rewrite.

    This is an alternative to configuring your server to parse .js files if you don’t have the ability to do this.

  3. Pingback: 10+ .htaccess snippets to optimize your website « The Blog of Jordan Rynard

  4. Pingback: .htaccess snippets to optimize your website « shankarsoma; Social Media & Digital Marketing Blog

  5. Pingback: Top .htaccess snippets to optimize your website | W3Corner

  6. Pingback: htaccess SEO: 10 suggerimenti utili « Seo

  7. Pingback: 11 tuyệt chiêu .htaccess tối ưu website của bạn | V-Share Team

  8. Pingback: 10 Useful .htaccess snippets Web Developer and Designer Should Know - Design Freebies

  9. Pingback: How to execute / run PHP code inside JavaScript files? « Technology Blog

  10. I’ve got an easy way without disturbing the .htaccess file. Is is very easy, just see how this works…

    //Here’s how to call a php file as javascript file

    //And this is the code of some_file.php file

  11. Pingback: 10+ .htaccess snippets to optimize your website | Justin Design and Coding Reference

  12. Pingback: Add PHP code witn Javascript « linthebell

Comments are closed.

Scroll to Top