Okay, 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.
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.
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.
plus…wouldnt you want YOUR copyrighted content copyrighted with the date from YOUR servers…just my thoughts
also…what about doing something like <link href=”javascript:document.write(‘NO_CLUE_WHY’);” /> im too lazy to test…just posing the thought
Cheers Louis for the tip.
Very odd work-around, but interesting none the less :)
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.
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.
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.
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.
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.
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.
How about SSI:
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
///////////////////////////////////////////////////////////////////////////
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.”
Interesting. I didn’t know those were supported by Apache. I’ll have to look into that a little more. Thanks for the info.
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:
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.
extremely weird…
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):
The material on this site began in 2008, so the copyright is a range that always stays current.
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.
Yeah, it’s kind of like node.js in a parallel universe. :)
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.
Not useless. I could use this to hide some proprietary calculations that are normally exposed when using straight up JavaScript. Decent tip.
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…
Thats a nice trick
i will use it for my projects too
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.
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?
I could use this to hide some proprietary calculations that are normally exposed when using straight up JavaScript….
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 !
Try this
function getTextBetweenTags($string, $tagname) {
$pattern = “/(.*)/”;
preg_match($pattern, $string, $matches);
return $matches;
}
$str = ‘Badakhshan
Badghis’;
$txt = getTextBetweenTags($str, “option”);
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:
get-local-time.php looks like this:
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.
Then your test.html file can look like this:
get-local-time.php looks like this:
The following will be displayed:
5:47 PM PDT America/Los_Angeles
Of course!!
You need to write:
Sorry…
I meant:
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!
I am trying those but not work for me.
I have really need for this.
Thanks
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.
I know this thread is super duper old. But just came by because I just read about this: http://news.softpedia.com/news/mosquito-exploit-stealing-legitimate-traffic-from-wordpress-and-joomla-websites-503647.shtml#sgal_0, and didn’t know that script tags could load anything besides .js files!
Thanks for the explanation.
despite lots of different ajax options and JS such as react, angular, etc… this is still helpful because you never know what kind of situation you could find yourself in. In my case I want to set variables for a p5js sketch that I want to build server side. The p5js is embedded in a react app but due to a number of idiosyncracies with p5js such as preload for images and reserved functions such as draw it is much easier to set this in a PHP file that I include as a js html tag src instead of via ajax. thanks!