Calling a PHP File From HTML’s Script Tag

on | 44 Comments

Calling a PHP File From HTML's Script TagOkay, admittedly, this is a pretty crazy and virtually useless tip. But it’s just one of those things that illustrates the flexibility of our craft and how sometimes solutions to problems can be found from some really outside-the-box thinking.

Back when I worked for a Toronto web design agency, we often had to update sites that were written in straight HTML, with no server-side programming at all. So every year, clients that owned such sites would ask us to update all the pages to display the current copyright year. That was pretty lame. Not exactly the kind of work we wanted to be doing.

So we wanted to create a way that the current year would be printed on each page automatically. But we didn’t want to include a JavaScript library, we didn’t want to use Ajax, and we wanted the year to come from the server, not the client.

So, one of our crafty PHP developers thought of doing this:

<script src="get-year.php"></script>

It’s just a regular HTML <script> tag that calls a PHP file instead of a JavaScript file. But there’s one catch: In that PHP file, you still have to use JavaScript. So we did something like this:

<?php

echo "document.getElementById('date-holder').innerHTML = '".Date('Y')."';";

?>

If you do just straight PHP, you won’t see any output, because the browser is expecting JavaScript. So, we give the browser JavaScript by echoing out the lines using PHP.

This allowed us to fulfil all of our requirements: We didn’t have to bother updating those copyright dates every year; we didn’t include any Ajax functions or any JavaScript library; and we retrieved the date from the server rather than the client.

Why Would You Need to Do This?

You probably wouldn’t. This is pretty useless for almost all projects because any project built in the last 5 or 6 years will be using some kind of server-side programming and/or a JavaScript library. So if a JS library is available, then you could just call the PHP file using Ajax.

But I thought this was a great example of some really crafty thinking, and it helped us get out of a little jam, while still utilizing server-side resources on a static site. It also minimized the amount of code used. And if nothing else, it’s interesting to see that the <script> tag can load pretty much any kind of file.

Are there any security issues with this? I really have no idea. I believe there are tracking applications and web counters that have used this approach. Would be interested to hear if anyone has any input on this.

Advertise Here

44 Responses

  1. bob:

    Wow, for a site called Impressive Webs, I didn’t expect something so… let’s say “unimpressive”.

    Why didn’t you want the date coming from the client again? Would have saved you an unnecessary network request if you didn’t have that requirement. It’s the same thing as doing an ajax request without all the ajax handling.

    Once you start using php, it isn’t really “static” either…

    • I didn’t think of the idea, bob. I just implemented it at the time. I’m completely aware of how useless this is, as I already stated in the article.

      JavaScript gets the date from the client’s system, whereas PHP gets it from the server. Yes, it’s extremely unlikely that there would be any difference between the two, but we just chose to do it that way, because… well, we could. :)

      It’s just a ridiculous hack that illustrates what’s possible with the script tag. I’m not advocating this method for getting date/time, I’m just illustrating that it’s possible to call any file using the script tag.

      • Joinkevich:

        Just thought I’d add — the script block is not actually processing any php (just in case a new web dev stumbles along this…). In fact, when you omit “type” from the script tag, standard browsers will assume “text/javascript”, but the browser doesn’t care about the src attribute’s extension (php). So the javascript is generated returned (probably as text/html?) and luckily browsers don’t care too much about the content type, otherwise this might not work! I wonder if adding the text/javascript header to the PHP file’s response might be necessary for some older or stricter browsers though…

        In fact, you should be able to just use <script src=’some-file.html’></script>, and the browser will try to parse the contents of the HTML file as Javascript. Of course, HTML files don’t usually include server side processing (some exceptions!) and the cool thing about using a php file is that it’s automatically handled by PHP and so you can do things like get the server time, or request a new webpage and tell javascript to write it into the document (thereby getting around cross-site scripting restrictions).

        Also, as for the date coming from the server rather than the client, I think that’s a good idea. It is a copyright after all. If it’s expired (or appears expired to the user who has his or her system time set back by a few years for some stupid reason), then … well… that would be stupid. Not sure if anyone would be able to use the copyrighted work and claim it had expired (and they could always modify the source of the page to display whatever the hell they want)… but still… using the server date gives the programmer better control over the page look. And it won’t be able to show up in search engine results with the wrong copyright date (actually may show with none at all if JS is not evaluated by the spider…)

    • I don’t actually think it’s appropriate to get a copyright date from a client’s system. If the system date were, say, a year ahead, the copyright date would appear to be a year in the future, which would look weird and unprofessional. Admittedly there would be no legal implications that I’m aware of, but it would still be undesirable. The risk might be small, but why take it when you could avoid it? IMO, they chose the right course of action.

      • jack:

        plus…wouldnt you want YOUR copyrighted content copyrighted with the date from YOUR servers…just my thoughts

        • jack:

          also…what about doing something like <link href=”javascript:document.write(‘NO_CLUE_WHY’);” /> im too lazy to test…just posing the thought

  2. Darren:

    Cheers Louis for the tip.
    Very odd work-around, but interesting none the less :)

  3. Not useless. I could use this to hide some proprietary calculations that are normally exposed when using straight up JavaScript. Decent tip.

    • It is useless, because you could just do that with Ajax instead. It’s just that in the situation we were in, it was impractical to use Ajax because we would have to include either a JS library on every page (way too much of a resource for something so simple) or else a bunch of old-school Ajax functions.

      • I wouldn’t call it useless in your case. Especially if it solved a problem.

        • Yes, that’s true. But I’m talking about the fact that it’s mostly useless today, because it’s very unlikely that you’d have no JS library and no back-end language to work with right on the page.

          • Steven:

            Very handy if you want to mix small javascript-generated content with static html. Especially if your static pages are cached from PHP CMS etc, as you can talk directly to thwe CMS without the latency of doing it directly. Best of both worlds, if done properly.

            Thanks.

  4. I’ve used a similar idea on an account overview page (that was also redirected to after the account creation page). The javascript got the creation date of the account (and number of views of that particular page) with sessions from the database, then wrote those values to a javascript file. If JS detected that the account was less than 5 minutes old and that the page had been viewed 2 times or less (due to refreshes, coming back to the overview page via link, etc) it showed a welcome message. If not, it didn’t.

    I chose to do it that way because 99% of the time I knew we wouldn’t show that message, and I didn’t want the server having to check ti all the time for every single page load, and let the client handle the decision making and showing (or not) of content.

    May not be anything cool or a great solution, but I am reminded of the similarities.

  5. I would also recommend adding a header() call to declare the content type within the php. Although the script tag likely guesses it correctly, it never hurts to be more thorough.

    This isn’t entirely uncommon. Similar can be done with css as well for different theming.

  6. What about running the date ‘code’ as an iframe instead?

    That way you don’t have to have any javascript at all. And I cannot think of any browser that does not support iframes.

    • You’re right, I can’t think of any reason why that wouldn’t have worked. At that time, we were coding XHTML-strict pages regularly, so although those older sites weren’t XHTML-strict, we weren’t really using old-school methods and deprecated tags (like iframe). So, between the three of us that were involved, I guess we didn’t think of that.

      But definitely an option in that case, and as far as I can tell, pretty much has the same result. And has the added benefit of not relying on JavaScript, so that actually seems like a stronger solution for that bizarre circumstance.

      • rl435:

        The iFrame isn’t depricated. You may not like it, but it is part of the HTML5 standard … sorry, just being picky.
        I don’t think your idea is as bad as it sounds. The post kept me interested. If I didn’t see some merit in it, I wouldn’t have made it this far down the page ;-)

        • Oh, of course. I was referring to a team I was working on around 2008, before HTML5 went into common use. At that time, we were doing our best to follow the standards, and if something was deprecated, then we didn’t use it, assuming it would not be future-proof. Of course, that turned out to be completely wrong, and it’s a good thing we don’t have the draconian rules of XHTML to follow anymore.

  7. How about SSI:

    
    <!--#config timefmt="%Y"-->
    <!--#echo var="DATE_LOCAL" -->
    

    Not tested, but you get the idea.

    • From what I understand, not all servers support those, and they’re even less common nowadays.

      • Maybe you prefer XSSI then:

        Listing 6. Sitewide copyright notice redux

        
        <!--#config timefmt="2003-%Y" --> <p>©<!--#echo var="DATE_LOCAL" --> 
           Kostas Pentikousis. All rights reserved.</p>
        

        ///////////////////////////////////////////////////////////////////////////

        http://onlamp.com/lpt/a/6012

        “Apache XSSI Advantages

        Many web developers resort to more sophisticated technologies–dynamic content management systems such as PHP-Nuke on the one hand and web site development and delivery engines including Mason, Cold Fusion, and Lotus Notes/Domino on the other–and discount XSSI as “simplistic” and “limited.” This is, to some extent, true.
        [...]
        Nevertheless, this is by no means the whole story. XSSI has many features, including pattern matching. Many web sites work just fine without a database back end, especially if they use the database simply to store documents. In fact, you can even build a light content management system using XSSI.”

    • I tried the SSI solution, but there’s a catch. If you want to show the time with your DATE_LOCAL, you get your ISP’s local time, not yours, even if you set the following in the .htaccess file:

      SetEnv TZ America/Los_Angeles

      If you’re using PHP, though, this works. But of course, in PHP, you have the option of setting the time zone in the code.

  8. hadrien:

    extremely weird…

  9. Even weirder, I could’ve sworn that the copyright year doesn’t need to be nor shouldn’t be updated to the current year; just the year the current site was created and published.

    • Well, those requests came from the project managers, who get them from the client. So I wasn’t in a position to say “That’s not correct.” :)

      But yes, I agree, which is why I prefer to do it this way (like on this site’s footer):

      
      Copyright &copy; 2008 - <?= Date('Y'); ?>
      

      The material on this site began in 2008, so the copyright is a range that always stays current.

  10. Ok now I can see where this could grow to be something more. A php library to do javascript dom manipulation.

    $dom(‘#thing’)->text(getThingValueFromMysql($thing_id));

    would output all the javascript stuff to make this happen.

    Sort of like doing jquery on the backend.

  11. first: this is far from impressive, sorry. the reason is not that the idea is bad, but that you actually writing about something without giving a worthy example of implementation. seems like a great tutorial of css3 round-corners, demonstrated using fonts..

    as to a good implementation:
    when you shop walmart, compusa.com and other distributors, you see it in action. many of microsoft’s and HP’s products there are actually injected by scripts.
    try disabling js for those site and you will be surprised.

  12. Not useless. I could use this to hide some proprietary calculations that are normally exposed when using straight up JavaScript. Decent tip.

  13. Rebecca:

    I think some might be missing the point here… This is just a simple example of something that was crafted out of necessity in a nick of time. Our craft is one that *should* make us go *beyond* what’s proposed here in an attempt to make best use of what’s been given to us as knowledge (and every little bit counts!).

    Unimpressive? Far from it, think again… This opens the possibility to have JS scripts that would contain stuff you have on your database easily!

    You can also “mask” the way you are creating this javascript code by means of an .htaccess RewriteRule condition. We are talking about dynamic Javascript here!

    A javascript that’s specifically tailored, server side, to the user’s grants/access levels/permissions, one that might include information pertaining said user and can be easily used to set up/configure other JS scripts (Last unit positions on a game, a to-do list for this date from a bigger task list, the specific configs saved for this user’s selected options for his/her WYSIWYG editor or profile image slider). How about you have a table with the localized language strings, where you could add new entries and get others to help you translate to many other languages?, A simple database query can call all of them and have your script localized in any available language. You could also cache the results server side as well, making deployment of localized custom scripts far easier than it was before.

    Maybe this *could* also simplify the process of sharing data between a JS and PHP and/or any templating system available.

    As for security, well, you’d still be able to code up input cleaning, xss-avoiding stuff, just like you’d do with any php.

    Yes there might be other ways to achieve the same tasks, and that there might be even far more interesting or complex examples that would harness this idea’s full potential…

  14. Thats a nice trick

    i will use it for my projects too

  15. Hey Louis, I used the same trick in getting the JavaScript content from the server. As all of us know each and script tag inclusion in html makes an http request to the server and makes page loading slow and I was having lot of individual JavaScript files. So to reduce http requests to server I created an php file to combine all the JavaScript files together, then I included single script tag by calling that php file.

    I think this the best way to combine the JS files as single.

    The next question is why should I have multiple JS files instead of having single JS file? I was having separate separate modules in different JS files and was creating the single JS file and didn’t want to mix-up the things.

  16. Ricky:

    Nice. Never hurts to learn useful little bits of trickery.

    I might be wrong but shouldn’t you set the php headers to the appropriate data type so that the browser interperts the incoming data as javascript?

  17. I could use this to hide some proprietary calculations that are normally exposed when using straight up JavaScript….

  18. That is what I am using on my html pages.
    While it is true that an iframe would not require javascript it’s a bit hard to place in a middle of text and wouldn’t work on a small phone screen as my site does.
    I am also using it for other applications, that allow to have a page loading very fast as the “optional” features load in the background.
    So it is cetainly NOT useless !

  19. Try this
    function getTextBetweenTags($string, $tagname) {
    $pattern = “/(.*)/”;
    preg_match($pattern, $string, $matches);
    return $matches;
    }
    $str = ‘Badakhshan
    Badghis';

    $txt = getTextBetweenTags($str, “option”);

  20. OK, I set up a couple of test files to check this out, but it fails to run as expected. My HTML file looks like this:

    
    <html>
    <body>
    <p><script src="get-local-time.php"></script></p>
    </body>
    </html>
    

    get-local-time.php looks like this:

    
    <?php  
    echo "document.getElementById('date-holder').innerHTML = '"
           . date("g:i A T e") . "';";  
    ?>
    

    I tried running this, but the time does not display. Is my HTML file set up correctly? Is there something I need to set in .htaccess to make this work?

    • I came up with an alternative solution utilizing SSI and a PHP file. It’s a little cleaner, and it works on my host. It does require that you set up SSI on the server. The first two lines I added to .htaccess turn on SSI for .html files. The SetEnv line in .htaccess allows me to display my own local timezone on my page instead of my ISP’s.

      
      Options +Includes
      AddOutputFilter INCLUDES .html
      SetEnv TZ America/Los_Angeles
      

      Then your test.html file can look like this:

      
      <html>
      <body>
      <p><!--#include file="get-local-time.php" --></p>
      </body>
      </html>
      

      get-local-time.php looks like this:

      
      <?php  
      echo date("g:i A T e");  
      ?>
      

      The following will be displayed:

      5:47 PM PDT America/Los_Angeles

    • What.Next:

      Of course!!
      You need to write:

      
      
      <html>
      <body>
      <p><script src="get-local-time.php"></script></p>
      </body>
      </html>
      
      
      
      • What.Next:

        Sorry…

        I meant:

        
        
        <html>
        <body>
        <p id="date-holder"><script src="get-local-time.php"></script></p>
        </body>
        </html>
        
        
        
  21. carlos r garcia:

    When it comes to how my little mind grasp a concept, this one is by far the best tip on including a php file in this manner.

    Give this man a ****** raise!

  22. I am trying those but not work for me.
    I have really need for this.

    Thanks

  23. mrtrash:

    It’s not usesless, it’s called JSONP, and it’s main advantage over ajax is no ‘same origin policy’ restriction. CORS is supported only on modern browsers whereas JSONP should work on allmost anything.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field. If you use keywords, your comment will be deleted, or your name will be replaced with the alias from your email address. No foul language, please. Thank you for cooperating.

Instructions for code snippets: Wrap inline code in <code> tags; wrap blocks of code in <pre> and <code> tags. When you want your HTML to display on the page in a code snippet inside of <code> tags, make sure you use &lt; and &gt; instead of < and >, otherwise your code will be eaten by pink unicorns.