--
--
結論
- 主要作用在提昇 PHP 執行效能,以及簡易的程式加密
- 使用 OpCode 加密可以保護程式邏輯,不能保護「程式內的字串」
--
php.ini
1 |
# vi /etc/php/7.4/apache2/php.ini |
1 2 3 4 5 6 7 |
[opcache] opcache.enable=1 opcache.save_comments=0 opcache.file_cache=/opt/Server/OpCache opcache.validate_timestamps=0 opcache.revalidate_freq=0 opcache.max_accelerated_files=4000 |
- opcache.enable=1 ; 啟用 OpCache
- opcache.save_comments=0 ; 關閉 comments
- opcache.file_cache=/opt/Server/OpCache ; 設定 OpCache Cache 路徑
- opcache.validate_timestamps=0 ; 關閉檔案更新檢查,配合下面的程式保護
- opcache.revalidate_freq=0 ; 檔案更新檢查時間
- opcache.max_accelerated_files=4000 ; 最大 cache 檔案數,需要大於總 .php 數量
重新啟動 apache2 服務
1 |
# systemctl restart apache2 |
--
保護程式作法
先將所有 .php 檔案編譯成 OpCache 之後就可以將 .php 原始碼檔案清空或是填入不相關內容
使用 PHP 官網範例稍加修改,將 require_once 替換為 opcache_compile_file(),官網有針對兩者之間的差異說明,請根據實際情況選用
1 2 3 4 5 6 7 8 9 |
<?php opcache_reset(); $directory = new RecursiveDirectoryIterator(__DIR__ . '/'); $fullTree = new RecursiveIteratorIterator($directory); $phpFiles = new RegexIterator($fullTree, '/.+((?<!Test)+\.php$)/i', RecursiveRegexIterator::GET_MATCH); foreach ($phpFiles as $key => $file) { opcache_compile_file($file[0]); } |
在網路根目錄執行以下執行即可將所有 .php 檔案內容清空
1 |
# find -name '*.php' -type f -exec sh -c 'echo "<?php" > {} ' \; |
--
更新
因為使用了禁用時間戳檢查,以及將原始碼清空,因此更新時,必須由開發主機提供 .php.bin 檔,OpCache 檔案皆是 www-data 使用者權限,可以使用 tar 打包及還原
.php.bin 檔案更新後,必須使用 opcache_reset() 或 opcache_invalidate() 來啟用新的 .php.bin 檔
--
計算 php 檔案數量
1 2 |
# find -name '*.php' -type f | wc -l 766 |
--
OpCache 長相
節錄內容
--
Preload
PHP 7.4 增加了 opcache.preload & opcache.preload_user 參數,因為原始碼後來會清空,因此不適用此參數
--
1,964 total views, 1 views today