如何使用phpBolt成功加密混有HTML标签的PHP文件?
phpBolt加密PHP与HTML混写文件失效问题
问题现象
使用phpBolt加密.php文件时,仅包含纯PHP代码的文件加密后可正常运行,但PHP与HTML混合编写的文件加密后无法正常生效。
当前使用的加密脚本代码如下:
<?php /** * src : source folder * encrypted : Output folder */ $src = 'src'; $php_blot_key = "kyc7fh"; /** * No need to edit following code */ $excludes = array('vendor'); foreach($excludes as $key => $file){ $excludes[ $key ] = $src.'/'.$file; } // $rec = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( $src )); $rec = new DirectoryIterator($src); $require_funcs = array('include_once', 'include', 'require', 'require_once'); foreach ($rec as $file) { if ($file->isDir()) { $newDir = str_replace( 'src', 'encrypted', $file->getPath() ); if( !is_dir( $newDir ) ) mkdir( $newDir ); continue; }; $filePath = $file->getPathname(); if( pathinfo($filePath, PATHINFO_EXTENSION) != 'php' || in_array( $filePath, $excludes ) ) { $newFile = str_replace('src', 'encrypted', $filePath ); copy( $filePath, $newFile ); continue; } $contents = file_get_contents( $filePath ); $preppand = '<?php define("PHP_BOLT_KEY", "kyc7fh"); bolt_decrypt( __FILE__ , PHP_BOLT_KEY); return 0; ##!!!##'; $re = '/\<\?php/m'; preg_match($re, $contents, $matches ); if(!empty($matches[0]) ){ $contents = preg_replace( $re, '', $contents ); ##!!!##'; } /*$cipher = bolt_encrypt( "?> ".$contents, $php_blot_key );*/ $cipher = bolt_encrypt( $contents, $php_blot_key ); $newFile = str_replace('src', 'encrypted', $filePath ); $fp = fopen( $newFile, 'w'); fwrite($fp, $preppand.$cipher); fclose($fp); unset( $cipher ); unset( $contents ); } $out_str = substr_replace($src, '', 0, 4); $file_location = __DIR__."/encrypted/".$out_str; echo "Successfully Encrypted... Please check in <b>" .$file_location."</a></b> folder.";
加密后无法运行的混写文件示例
<html> <body> <h1> <?php echo "Hello Sarbaz Ali !!!"; ?> </h1> </body> </html>
加密后可正常运行的纯PHP文件示例
<?php echo "<h1> Hello Sarbaz Ali !!! </h1>"; ?>
问题解答
phpBolt支持加密PHP与HTML混写的文件,当前加密脚本存在两个核心逻辑错误,导致混写文件运行失败:
- 前置解密代码的
return 0;会直接终止执行流程
写入加密文件头部的解密代码携带return 0;语句,对于纯PHP文件,解密完成后执行return终止流程,本身没有输出逻辑所以看起来运行正常;但对于混写文件,解密完成后直接return,后续解密出的HTML内容、PHP逻辑根本不会被执行,自然无法正常渲染页面。 - 手动替换
<?php标签的逻辑会破坏混写文件语法结构
现有正则仅会替换文件中第一个匹配到的<?php标签,混写文件存在?>闭合标签、甚至多个<?php ... ?>代码块时,替换操作会打乱原有的PHP标签结构,导致解密后的代码出现语法错误。如果文件开头是HTML内容、没有前置的<?php标签,该逻辑还会完全不生效。
修复方案
调整两处核心逻辑即可支持混写文件加密:
- 删除头部解密代码中的
return 0;语句,保证解密完成后后续代码可以正常被解析执行 - 移除手动替换源文件
<?php标签的逻辑,直接将完整的原文件内容传入bolt_encrypt()加密即可,phpBolt本身可以正确解析混写的PHP/HTML语法,不需要提前修改源文件内容。
修改后的核心加密段代码参考:
$contents = file_get_contents( $filePath ); // 移除return 0,删除原有的preg替换<?php逻辑 $preppand = '<?php define("PHP_BOLT_KEY", "kyc7fh"); bolt_decrypt( __FILE__ , PHP_BOLT_KEY); ##!!!##'; $cipher = bolt_encrypt( $contents, $php_blot_key ); $newFile = str_replace('src', 'encrypted', $filePath ); $fp = fopen( $newFile, 'w'); fwrite($fp, $preppand.$cipher); fclose($fp);
额外注意:当前脚本使用DirectoryIterator只会遍历src根目录下的文件,不会递归处理子文件夹,如果需要加密子目录内的文件,换回注释掉的RecursiveIteratorIterator递归遍历逻辑即可。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

