在 PHP 開發中,為了保護原始碼或減小文件體積,開發者常使用 base64_encode 搭配 gzdeflate(或 gzinflate)進行壓縮編碼。被加密的文件通常以 <? eval(gzinflate(base64_decode(... 開頭。本文提供完整的編碼與解碼實作範例,幫助你快速掌握這項技術。
以下函式會讀取指定的 PHP 文件,移除註解與空白、剝離 PHP 標籤,然後進行 gzdeflate 壓縮並以 base64_encode 編碼,最後產生可直接執行的加密文件:
<?php
function encode_file_contents($filename) {
$type = strtolower(substr(strrchr($filename, '.'), 1));
if ('php' === $type && is_file($filename) && is_writable($filename)) {
$contents = file_get_contents($filename);
// 檢查是否已加密,避免重複處理
$pos = strpos($contents, '/*Protected by 草名 https://www.crazyi.cn Cryptation*/');
if (false === $pos || $pos > 100) {
// 移除註解與空白
$contents = php_strip_whitespace($filename);
// 去除 <?php 和 ?> 標籤
$headerPos = strpos($contents, '<?php');
$footerPos = strrpos($contents, '?>');
$contents = substr($contents, $headerPos + 5, $footerPos - $headerPos);
// 執行壓縮編碼
$encode = base64_encode(gzdeflate($contents));
// 組裝最終可執行代碼
$encode = '<?php' . " /*Protected by 草名 https://www.crazyi.cn Cryptation*/\n eval(gzinflate(base64_decode(\"" . $encode . "\")));\n /*Reverse engineering is illegal and strictly prohibited- (C)草名 Cryptation 2008*/ \n?>";
return file_put_contents($filename, $encode);
}
}
return false;
}
// 呼叫範例
$filename = 'g:\\我的文檔\\桌面\\test.php';
encode_file_contents($filename);
?>
若需還原被加密的代碼,只需將編碼字串解碼並寫入文件:
<?php
$Code = '這裡填寫要解密的編碼'; // base64 編碼內容
$File = 'test.php'; // 解碼後儲存的文件名
$Temp = base64_decode($Code);
$temp = gzinflate($Temp);
$FP = fopen($File, "w");
fwrite($FP, $temp);
fclose($FP);
echo "解密成功!";
?>
注意事項:此類加密屬於混淆手段,無法提供絕對安全性。生產環境建議搭配 opcode 快取(如 OPcache)與代碼簽名機制,並留意 eval() 的安全風險。