Wednesday, March 20, 2013

Protect Your External CSS and Javascript Codes? Possible?


Actually there is no way to protect your Javascript or CSS from being seen.

I've explained a way to sort of protect it from Safari/Firefox/IE in:


http://webtrick101.blogspot.com/2012/08/protect-your-css-and-javascript-codes.html


Nevertheless Chrome can easily show your CSS/Javascript codes to the world.


Since there is no way to block it, you might as well minify your Javascript/CSS codes. In that way, your codes will be harder to be understood and may sway some programmers from getting what they want easily.


Here's a simple way to minify it before you show it to the world using PHP:


Please remove all the comments from your CSS/Javascript codes before using the following minification codes.



For mycss.php:

<?php

error_reporting(0); // make sure it is not reporting any warning that will ruin the output
if (preg_match('/xxx.xxx.xxx.xxx/',$_SERVER['REMOTE_ADDR'])) {

$css = <<<MYCSS
a {text-decoration:none;color:#777777;}
.
.
.
MYCSS;

echo(preg_replace('/[\r\n\t]/','',$css)); // simple minification

}

?>



For myjs.php:

<?php

error_reporting(0); // make sure it is not reporting any warning that will ruin the output
if (preg_match('/xxx.xxx.xxx.xxx/',$_SERVER['REMOTE_ADDR'])) {

$js = <<<MYJS
var ie=0;
.
.
.
MYJS;

header("Content-type: application/x-javascript"); // to make sure browser sees it as js
echo(preg_replace('/[\r\n\t]/','',$js)); // simple minification

}


?>


Please note that this is just a simple minification to remove newlines and tabs using PHP's preg_replace. Spaces are not removed due to the 'var ' problem. If the spaces are removed, 'var' will merge with the variable name next to it. This can be solved by several filters to remove other spaces but it is not the purpose of this post to go deep into minification. I better call it "mini minification"! :)

P/S: If you want to retain your comments before sending to the minification process, this can be achieved by removing all the comments using preg_match before the minification.

UPDATE on 1st of April 2013
You can remove the javascript comments by using this preg_replace in PHP:
$js = preg_replace('|//[^\r^\n]+(\r\n)|','',$js);

UPDATE on 17th of April 2013
Sorry if you were using a Unix/Linux based web server, you'll need these to get rid of the comments instead of the codes above:
$js = preg_replace('|//[^\n]+(\n)|','',$js);

To simplify the consistency between both server platforms (MS/Linux), include both filter codes above to remove the comments before minify your javascript.

No comments:

Post a Comment