Obfuscate php code
A class to obfuscate php code:
if (!defined('T_ML_COMMENT')) {
define('T_ML_COMMENT', T_COMMENT);
} else {
define('T_DOC_COMMENT', T_ML_COMMENT);
}
class ofusca {
var $target = '/var/www/target';
var $source = '/var/www/source';
var $variables = array();
var $n = 0;
private function output($file) {
return $this->target.str_replace($this->source,'',$file);
}
public function __construct() {
$this->readdir($this->source);
}
private function readdir($dir) {
@mkdir($this->output($dir), 0777);
$directory = dir($dir);
while ($file = $directory->read())
{
if ($file!="." & $file!=".."){
if (is_dir($dir.'/'.$file)) {
$this->readdir($dir.'/'.$file);
} else {
$ext = substr($file, stripos($file,'.'));
$this->parse($dir.'/'.$file, $ext);
}
}
}
$directory->close();
}
function callback_variables($matches) {
$var = $matches[0];
if (array_key_exists($var, $this->variables)) {
return $this->variables[$var];
} else {
$this->n = $this->n + 1;
if (($var!='$this') && ($var!='$this')) {
$this->variables[$var] = '$v'.$this->n;
return $this->variables[$var];
} else {
return $var;
}
}
}
function strip_comments($source) {
$tokens = token_get_all($source);
$ret = "";
foreach ($tokens as $token) {
if (is_string($token)) {
$ret.= $token;
} else {
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_ML_COMMENT:
case T_DOC_COMMENT:
break;
default:
$ret.= $text;
break;
}
}
}
return $ret;
}
private function parse_array_php($miarray) {
$text = $miarray[1];
$text = '<?'.$this->parse_php($text).'?>';
return $text;
}
private function parse_php($text) {
//strip comments
$text = $this->strip_comments($text);
//remover tabs
$text = preg_replace('/([\t])*/', '', $text);
//remover intros
$text = preg_replace('/([\r\n])/', ' ', $text);
//remover dobles espacios
$text = preg_replace('/([ ]{2,})/', ' ', $text);
//cahnge vars
$text = preg_replace_callback('/\$[a-zA-Z]+/', array($this,'callback_variables'), $text);
return trim($text);
}
private function parse($file, $extension) {
echo $file.'<br>';
$text = file_get_contents($file);
switch ($extension) {
case '.php':
$text = $this->parse_php($text);
break;
case '.html': //views
$text = preg_replace_callback('|\<\?([\=]?(php)?[^>]+)\?>|', array($this,'parse_array_php'), $text);
break;
}
file_put_contents($this->output($file), $text);
}
}
By Efra, published on October 31, 2010