cooking, programming and everyday life xrado

Thursday, December 13, 2007

PHP / Javascript Obfuscator

Have you ever want to prevent others sticking their fingers into your code? I did. I have searched over the web, but i didn't find anything suitable. Actually i didn't want to protect my code, but just make it harder to read and modify. So i made small script that do just that. The script strips all new lines, tabs, unneeded spaces and comments, so the code is braked in to one line. I didn't forget about php "here document" that i use quite a lot. This one needs new line right after the terminator, so if you using it, the output will have some more lines on the end.

I run this script from the linux shell as you see below, stored in to file comp.php. Just "cd" to directory where you have your php or js scripts and run the command. Find will recursively found all the *.php scripts and obfuscate them. Be careful before running the script!!! Always check the path you are in and do a backup copy, otherwise you might end up with a headache or even losing the code.

find . -iname "*.php" -exec php comp.php {} \;
find . -iname "*.js" -exec php comp.php {} \;
// here document terminator
$here_document = "END";


if(ereg($argv[0],$argv[1])) exit();

function cleanup($line){
	$line = preg_replace('/(^|\s)\/\/(.*)\n/','',$line); // remove line comments // comment
	$line = preg_replace('/(\t|\r|\n)/','',$line);  // remove new lines \n, tabs and \r
	return $line;

$lines = file($argv[1]);
echo $argv[1]." ";
echo "lines: ".count($lines)." -> ";
foreach ($lines as $line) {
        if(ereg($here_document,$line) && ereg("<<<",$line)) $out.= cleanup($line)."\n";
        else if(ereg("$here_document;",$line)) $out.= "\n".cleanup($line)."\n";
        else $out.= trim(cleanup($line))." ";
$out = preg_replace('/(\/\*[\s\S]*?\*\/)/', '', $out); // remove multi-line comments /* */

file_put_contents($argv[1],trim($out));	// store back to file

echo count(file($argv[1]))."\n";
Source: comp.php.txt