2

When my scripts are done, I want to optimize/convert them to smaller size + its harder to get know what do the files even they are stolen.

$c = file_get_contents('source.php');

$newStr  = '';
$commentTokens = array(T_COMMENT);
if (defined('T_DOC_COMMENT'))
    $commentTokens[] = T_DOC_COMMENT; // PHP 5
if (defined('T_ML_COMMENT'))
    $commentTokens[] = T_ML_COMMENT;  // PHP 4
$tokens = token_get_all($c);
foreach ($tokens as $token) {
    if (is_array($token)) {
        if (in_array($token[0], $commentTokens))
            continue;
        $token = $token[1];
    }
    $newStr .= $token;
}

$newStr = str_replace (chr(13), '', $newStr);
$newStr = str_replace (chr(10), '', $newStr);
$newStr = preg_replace('/\s+/', ' ', $newStr);

now $newStr contain the "compressed" stuff. Almost OK, but it kills to much white spaces. If there are white spaces in code like this:

if (true)
   {
        codeeee();
   }

it converts to:

if (true)
{
codeeee();
}

and thats ok. But in case of this:

$a = '      var          ';

it does:

$a = ' var ';

which is unwanted. How to do this optimize correctly? Are there any ideas? I almost thinking of renaming class names etc.

John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 4
    Just use an obfuscator / code encoder solution if you really have to. – Pekka May 31 '12 at 12:21
  • 2
    You want to protect your code or you want to optimize it? You cannot really do both at the same time, and either one will be quite limited. – tereško May 31 '12 at 12:24
  • yea obfuscator. Unfortunatly I only seen online versions... – John Smith May 31 '12 at 12:37
  • 1
    This thread has a lot of suggestions for obfuscation software you can download (very low signal to noise ratio, though, but there is some helpful stuff you can try.) http://stackoverflow.com/questions/232736/code-obfuscator-for-php – poundifdef May 31 '12 at 12:43

1 Answers1

1

With help from this answer I was able to create this regex which trims all whitespace (including line breaks) down to single spaces, but preserves the whitespace between quotes (either ' or ")

preg_replace('/\G(?:"[^"]*"|\'[^\']*\'|[^"\'\s]+)*\K\s+/', ' ', $string);
Community
  • 1
  • 1
Timm
  • 12,553
  • 4
  • 31
  • 43