473,804 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to minify (not obfuscate) your JavaScript using PHP

hsriat
1,654 Recognized Expert Top Contributor
For a good programmer, providing good comments in the code is a must. In PHP, giving comments has no demerits. But what about JavaScript? Do you really want those comments to stay in the code and make it double in size, and of course disclose what you have done when the code reaches the client (browser)?

I am not sure how many of you would have faced this problem, but I faced this many times. I am not good at memorizing things, so I give lot of code comment in my JavaScript code. And never wanted that comments to reach the client. So I used to remove comments from each file by a PHP code and then upload that minified file to the server.

Then an idea came across my mind. And I never removed comments afterwards. May be some of use would already be using this thing, but it's new to me, so thought of posting here.

Here it is...
  • Instead of a regular name folder eg. js or scripts, in which you save your JavaScript files, save them in a random name folder. Something like js_kl32lnfdn.
  • We call our external JavaScript files as
    Expand|Select|Wrap|Line Numbers
    1. <script type="text/javascript" src="/scripts/myscript.js"></script>
    Instead of this, make a PHP function, something like this:
    Expand|Select|Wrap|Line Numbers
    1. function send_script($script)
    2. {
    3.     echo "<script type=\"text/javascript\" src=\"/js.php?js=".$script."\"></script>"; 
    4.     //don't use the XML style closing tag (<script ....  />) IE would not read it.
    5. }
    6.  
    Keep this function in a saperate file.
  • In the root folder, save this PHP file (js.php)
    Expand|Select|Wrap|Line Numbers
    1. <?php
    2. //define the folder name, so that it can be changed anytime.
    3. define("FOLDER_NAME", "js_kl32lnfdn");
    4.  
    5. //path for the original file
    6. $js_original = $_SERVER['DOCUMENT_ROOT']."/".FOLDER_NAME."/".$_GET['js'];
    7.  
    8. //header for the javascript file (will give a warning if not provided)
    9. header("content-type:text/javascript; charset:UTF-8");
    10.  
    11. //alert error if file doesn't exisit
    12. if (!file_exists($js_original))
    13. die('alert(\'JavaScript file error!\')');
    14.  
    15. //include minificator class
    16. require('jsmin-1.1.0.php');
    17.  
    18. //read and minify the content
    19. $minified = JSMin::minify(file_get_contents($js_original));
    20.  
    21. //header for caching
    22. header("Expires: ".gmdate("D, d M Y H:i:s", (time()+9000)) . " GMT");
    23.  
    24. //year to write on copyright notice
    25. $year = getdate();
    26. $year = $year['year'];
    27.  
    28. //send your copyright notice
    29. echo "/* Copyright ".$year." - www.your-website.com */";
    30.  
    31. //send the minified version
    32. echo $minified;
    33. ?>
    34.  
    The minificator PHP class is here: JSMin

What will happen is..
  • The JavaScript file will get minified by the js.php file, which in itself will use a minificator class (not made by me).
  • A file with path js_kl32lnfdn/script1.js will be called as js.php?js=scrip t1.js. So one would never come to know the path to the original (commented) file.
  • For futher security, like if you only want the logged in user to be able to call the javascript or other things, you can add some verification code just in the starting of the js.php.


Hope you will like it.

Regards,
Harpreet
May 20 '08 #1
2 11640
Markus
6,050 Recognized Expert Expert
Not sure why you wouldn't want a client to be able to read the comments?
Jun 24 '08 #2
hsriat
1,654 Recognized Expert Top Contributor
Just in case your comments are making your JS too bulky. For instance, for a complex DHTML page (like gmail, yahoomail), comments can make your JS to reach double in size than without comments. And of course it makes you code a bit uninterpretable .

_______________ _______________ ____________

A little addition to the above js.php code, on the very first line:
Expand|Select|Wrap|Line Numbers
  1. if (!isset($_GET['js']) || $_GET['js']=="")
  2. die('alert(\'JavaScript file error!\')');
Jun 28 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
4259
by: mthlv12 | last post by:
I am using the latest version of eclipse to develop a java application. Is there an obfuscate button in eclipse ?
20
3307
by: twigster | last post by:
Hey everyone, I'm looking for a good way to obfuscate some Javascript code. Does anyone have a good experience or bad experience with a particular software? thanks
2
3714
by: Laurent Bugnion [MVP] | last post by:
Hi group, A few years ago, I translated Douglas Crockford's JsMin from C to C#, because we wanted to use this functionality in our build process. JsMin is a code minimizer for JavaScript. It will remove all comments, empty lines, turn tabs into single spaces, etc... The goal is to reduce the size of JavaScript files to the minimum necessary, without modifying the functionality. Additionally to reducing the script's size, JsMin also...
1
4950
by: shapper | last post by:
Hello, Does anyone knows any C# Library to Combine and Minify CSS and Javascript files? I was able to find a few Rails and Java tools but no .NET tool. This would be really useful for ASP.NET web applications. Thanks, Miguel
50
3901
by: Martin Rinehart | last post by:
How much javascript would you have when you decide that minifying is called for?
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10350
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10096
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9174
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7638
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6866
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4311
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.