Grow your CSS skills. Land your dream job.

Last updated on:

Use PHP inside JavaScript

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.

Comments

  1. drivel
    Permalink to comment#

    Could you use this for stylesheets?

  2. Yasin
    Permalink to comment#

    Nice one can you give some explanatory example how all its work

  3. sam
    Permalink to comment#

    i dont think i can understand this without looking at a working example

  4. If I’ve understood it correctly, an example would be to have a file called:

    myjavascript.api.js

    Link to it in your HTML:

    <script src=’js/myjavascript.api.js’ type=’text/javascript’></script>

    Then, in the myjavascript.api.js itself, you can now use PHP code:

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

    // JS Code
    function myJavascriptFunction(variable) {
    // Do stuff with variable
    }

    myJavascriptFunction(<?php echo $variable_from_db; ?>);

  5. It quite valuable thing you shared as a trick and in some cases it will be really needed. However, before using it we have to clear what is more favorite for us: performance or this way to get PHP vars inside JS. Because when applying this trick, JS file is going to load much more slower, because it is loading as PHP file.

    Thanks anyway.

    • Sébastien
      Permalink to comment#

      In some other cases, it would be much faster… Avoiding a trip back to the server to fetch initialization data, which would also be php parsed.

      In the case of a single page app for example where you might need a configuration file loaded inside your app.js file of requires.

      On the other hand, you can put it in a data-attribute of a hidden div in your index.php file.

  6. Jon
    Permalink to comment#

    Does anyone know if this would work in a J2EE environment? I have a web application built in eclipse with JavaScript (jsp and jspf files) that I need to do some server stuff on the client side with Java and can’t get to the Java functions so I was going to try and use PHP to do it on the client side. Just some file manipulation…

    Thanks!
    Jon

  7. sentio
    Permalink to comment#

    can u post me all lastest updates in my mail,Thanx

  8. Permalink to comment#

    Awesome trick, :) I love it. Thanks

  9. Manish
    Permalink to comment#

    Please explain more because it’s not enough to understand.

    • I think I get it. What you’re doing is telling the server in htaccess to process any file with “api” in the name as php. This means if you had a file “myscript.api.js”, then when the server opened the file it would treat it as a php file and even say it was a php file. You don’t want your server to tell clients it is a php file though, because they’re expecting a javascript file. So the very first thing you do in the file is use php’s “header” function to set the content-type header back to “text/javascript”.

      So essentially in htaccess you tell the server: “Hey this javascript file is actually a php file because it has ‘.api.’ in the name.”

      Then when it’s parsing the file, you tell it: “Tell the client this is a javascript file.”

      You can also try going the other way around, serving “myscript.php” as a javascript file and using the header function to set it’s content type to “text/javascript”, but I’m not sure that works everywhere, and it definitely can confuse maintenance.

    • badmidget
      Permalink to comment#

      I’ll give you the example that brought me to this page.

      I have a whole bunch of web pages that link to one javascript file. The markup on those html pages can’t pull in a php page the same way they pull in my javascript file. However, it became necessary for me to build an admin page that would change certain parts of the javascript file. After a quick google search I found this page. Now I can create a php admin area to write to a database and use my php IN my javascript file to read those database values.

      Here’s how I did it:
      myfolder/myscript.js is what all the pages link to. so in ‘myfolder’, I made an htaccess file that has Chris’s code in it only I changed the ‘api’ to ‘MyWhackyExpression’.

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

      So then in my javascript file I put the doctype info like Chris says to do, but I added ‘//MyWhackyExpression’ to it.

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

      Now the htaccess file will will tell the server to process any file that contains ‘MyWhackyExpression’ as php even my javascript file, but browsers still see it as javascript. All of my php isn’t rendered out to the js file just like php isn’t rendered out to the browser with html.

  10. Gunasekhar
    Permalink to comment#

    not worked

  11. Iulian

    Hi!

    Nice trick and thanks for sharing! However I have a question, usually the .js and .css files tend to get cached by the browsers. In this case all the php code written in the file will be executed just once, first time the script file is loaded. Any ideas how to overcome this problem?

    • Joao
      Permalink to comment#

      you can do something like this:

      <?php
      echo '<script type="text/javascript" src="someJSFile.php?rand='.uniqid().'">';
      ?>
      
    • Remember that caching is a good thing. (Caching = fast = good).

      Appending a random string to the end of file names does break caching, so that might be good for development, but not so much for “live” websites. If you want to go down this road I might suggest setting a variable and using that variable at the end of your file names, so you can adjust in one place to break cache, but not break cache every single time.

    • Joao
      Permalink to comment#

      it was a problem for Iulian, so, problem solved :)

  12. Joao
    Permalink to comment#

    Hey!

    Why not include a php file like it was js

    <script type="text/javascript" src="someJSFile.php">
    

    and then

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

    you still can run php inside js, you don’t need to mess with htaccess and you don’t compromise performance.
    Thanks!

    • That would work, but I’d be careful saying “you don’t compromise performance.” You’re asking your server to process this file every single time it’s requested, rather than just serve it up. You might be fine doing it this way, but I suspect it’s not a common practice for that reason.

    • Annnnnd. Now I realize the snippet this comment is posted on is specifically about doing this exact thing. So yeah good call, you can do it just as you’ve described.

    • Joao
      Permalink to comment#

      Hey Chris!
      here,

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

      you’re asking the server to process the php/js file every single time it’s requested too… i don’t see any difference from the htaccess trick…

  13. Iulian
    Permalink to comment#

    Hello,

    It wasn’t a real problem. I just wanted to have a better image of the entire concept of using php in css and js. Personally I wouldn’t use this since is a performance issue as it was proved, but it’s a cool trick to have in your sleeve. :)

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".