Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

PHP: Simple javascript obfuscator (merging files)

Currently I'm working on a big JavaScript project. It has a lot of files that have to be compressed. I wrote a simple php class that merges all the files into one. It has also a useful simple obfuscator method.

The php class:

class JSComposer {
    function run($files, $output) {
      $numOfFiles = count($files);
      $jsStr = "";
      for ($i = 0; $i < $numOfFiles; $i++) {
        $file = $files[$i];
        $fh = @fopen($file, "r");
        if (!$fh) {
          die("Composer: error reading file '".$file.
            "'");
        } else {
          $jsStr. = fread($fh, filesize($file));
          fclose($fh);
        }
      }
      $fh = fopen($output, 'w') or die("Composer: unable to write !!!");
      fwrite($fh, $this - > filterResult($jsStr));
      fclose($fh);
    }
  
    function filterResult($jsStr) {
      $jsStr = preg_replace('~[^"\\'\\ (] // ([^\\r\\n]*)[^"\\'\\)]~', '/*$1 */', $jsStr);	
          $jsStr = str_replace("\\r", "", $jsStr);		$jsStr = str_replace("\\n", "", $jsStr);		$jsStr = str_replace("\\t", "", $jsStr);		$jsStr = str_replace(" = ", "=", $jsStr);		$jsStr = str_replace(") {", "){", $jsStr);		$jsStr = str_replace(" ( ", "(", $jsStr);		$jsStr = str_replace(" ) ", ")", $jsStr);		$jsStr = str_replace("; ", ";", $jsStr);		$jsStr = str_replace("if ", "if", $jsStr);		$jsStr = str_replace("for ", "for", $jsStr);		$jsStr = str_replace(" >= ", ">=", $jsStr);		$jsStr = str_replace(" + ", "+", $jsStr);		$jsStr = str_replace(" - ", "-", $jsStr);		$jsStr = str_replace(" * ", "*", $jsStr);		$jsStr = str_replace(" / ", "/", $jsStr);		$jsStr = str_replace(" || ", "||", $jsStr);		$jsStr = str_replace(" && ", "&&", $jsStr);		$jsStr = str_replace("try ", "try", $jsStr);		$jsStr = str_replace(", ", ",", $jsStr);		$jsStr = str_replace(" == ", "==", $jsStr);		$jsStr = str_replace(" != ", "!=", $jsStr);		$jsStr = str_replace(": ", ":", $jsStr);		$jsStr = str_replace("  ", "", $jsStr);		$jsStr = str_replace("   ", "", $jsStr);		$jsStr = str_replace("    ", "", $jsStr);		return $jsStr;	}}

And the usage:

$files = array("js/Application.js", "js/core/plugins/json2.js", "js/core/plugins/GoogleMaps.js", "js/core/plugins/jquery-1.4.4.min.js");
    $composer = new JSComposer();
    $composer - > run($files, "js/packed.js");

P.S.the obfuscator method converts short comments (//...) to long comments (/*...*/). If you have a url like "http://site.com" the script will also recognize it as a comment. That's why it's better to write your comment like that:

// my comment here

not:

//my comment here

So just add one more interval after "//".

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.