Detect PHP code in files with mixed content (PHP/HTML) by PHP for
Obfuscate?
You can use the PHP tokenizer extension to achieve this properly.An example is the function below :
function findPHP($string){
if(!is_string($string)) return false;
$tokens=token_get_all($string);
$php_code='';
$result=array();
$start=false;
foreach($tokens as $key=>$token){
if(is_array($token)&&token_name($token[0])==="T_OPEN_TAG"){
$start=true;
continue;
}
if(is_array($token)&&token_name($token[0])==="T_CLOSE_TAG"){
$start=false;
$result[]=$php_code;
$php_code='';
continue;
}
if($start){
if(is_array($token))
$php_code.=$token[1];
else
$php_code.=$token;
}
}
return $result;
}
print_r(findPHP(file_get_contents('get_path.php')));
This function detect only the PHP code in any file with mixed content and return an array containing all the PHP code occurences.
Then all you have to do is to use your offuscator as you want.All that said you can alter lightly the function above to achieve your purpose.Example:
function find_and_offuscate_PHP($string){
if(!is_string($string)) return false;
$tokens=token_get_all($string);
$php_code='';
$result=array();
$start=false;
$from=false;
foreach($tokens as $key=>$token){
if(is_array($token)&&token_name($token[0])==="T_OPEN_TAG"){
$from=$key;
$start=true;
continue;
}
if(is_array($token)&&token_name($token[0])==="T_CLOSE_TAG"){
$start=false;
$result[$from]=$php_code;
$from=false;
$php_code='';
continue;
}
if($start){
if(is_array($token))
$php_code.=$token[1];
else
$php_code.=$token;
unset($tokens[$key]);
}
}
if($start&&$from&&$php_code){
$result[$from]=$php_code;
unset($start,$from,$php_code);
}
// require_once 'plugins/Obfuscator.php';
$result=array_map(function($php_code){
// return new Obfuscator($php_code, 'Class/Code NAME');
return base64_encode($php_code);
},$result);
$tokens=array_map(function($token){return is_array($token)?$token[1]:$token;},$tokens);
foreach($result as $from=> $offuscated){
$tokens[$from] .= " $offuscated";
unset($result[$from]);
}
return join(' ',$tokens);
}
note that in this code i just use base64_encode for the test but i keep lines which use your own offuscator ,you just need to uncomment then and the function will be ready to use in your app.