多專案 函式庫、類庫 統一為一個版本的方法
現在 手裡 有好幾個 專案在進行,每個專案都有部分通用的程式碼,只想維護一個 函式庫、類庫,並且每個專案都不想有冗餘程式碼,函式功能更新後,其他專案的函式也需要更新。晚上抽空寫了個 簡單的打包小指令碼:one.php,以後 更新函式或類時,只需要在唯一的 函式庫、類庫 中更新,其他專案使用 打包後的 php 指令碼即可(理論上也能提高PHP的執行速度,只需要載入、分析一個檔案)。
因為我的 函式庫、類庫都在一個目錄下,所以沒有針對相對路徑 做處理(懶),cmd 進入 core 目錄,執行 php one.php 即可按規則打包成一個獨立的檔案,執行效果如下。
打包流程,以 public.php 為例。
現在功能有限,僅支援 同一個目錄(因為我只用到了單目錄),如果有哪位大神 在此基礎上修改了多目錄版本,請一定要分享一分給我。
至於用處,除了 方便維護多個專案(A專案、B專案)或同一個專案的多個版本(比如:VIP版、普通版),最大的用處,可以用於商業版程式混淆加密。比如商業軟體:index.php,product.php 每個檔案都打包混淆加密,每個檔案都包含了所有的程式碼(幾萬行)。破解者解密後,看到幾萬行程式碼,上百個函式(可能都還有用),同一個功能,各個檔案內的函式名都不一致,會哭死的。。。。
測試包下載地址:
one.php 原始碼: ofollow,noindex" target="_blank">http://www.miaoqiyuan.cn/products/onephp.rar
<?php /** * 類名:One * 作者:mqycn * 部落格:http://www.miaoqiyuan.cn * 原始碼:http://www.miaoqiyuan.cn/p/one-php * 說明:多專案 函式庫、類庫 統一為一個版本的方法 */ class OneFile { //已經合併的檔案 public static $includes; //處理一個檔案 public static function run($index_file, $output_file) { self::$includes = array(); self::log('Input', $index_file); $output = self::parse($index_file); file_put_contents($output_file, self::repair($output)); self::log('Output', $output_file); } //分析PHP檔案 public static function parse($file) { if (empty(self::$includes[$file])) { self::log('Append', $file); self::$includes[$file] = true; $code = file_get_contents($file); if (preg_match_all("/(require_once|require|include_once|include)\s+'([^']*)';/", $code, $match)) { for ($i = 0; $i < count($match[0]); $i++) { $code = str_replace($match[0][$i], self::parse($match[2][$i]), $code); } } return $code; } else { self::log('Ignore', $file); return ''; } } //程式碼修復 public static function repair($code) { $php_prefix = "<?php\r\n"; $php_suffix = "\r\n?>"; $code = str_replace("\n", "\r\n", $code); $code = str_replace("\r\r\n", "\r\n", $code); $code = str_replace($php_prefix, '', $code); $code = str_replace($php_suffix, '', $code); for ($i = 0; $i < 5; $i++) { $code = str_replace("\r\n\r\n", "\r\n", $code); } return $php_prefix . $code . $php_suffix; } //輸出日誌 public static function log($type, $text, $status = '') { if (in_array($type, array('Append', 'Ignore'))) { $status = "- ${type}"; $type = "|-- "; } else { $type = "${type}:"; } echo "${type} ${text} {$status}\r\n"; } } OneFile::run('vip.php', '../vip.php'); OneFile::run('public.php', '../public.php');