新聞中心
簡(jiǎn)介
OPCODE是PHP編譯后的二進(jìn)制代碼,生成的Opcode作為一種中間語(yǔ)言,可以幫助實(shí)現(xiàn)PHP源程序代碼的不開(kāi)源,當(dāng)然,這種代碼也很容易被反編譯,不過(guò)對(duì)于一些簡(jiǎn)單的場(chǎng)景也是很足夠了。
編譯的基本思路是首先在php.ini中配置加載opcache擴(kuò)展,并配置相關(guān)參數(shù),然后執(zhí)行一個(gè)PHP腳本遍歷源代碼目錄,并進(jìn)行編譯,核心的函數(shù)是opcache_compile_file(),該函數(shù)會(huì)根據(jù)php.ini中的參數(shù),編譯并輸出二進(jìn)制代碼。
成都創(chuàng)新互聯(lián)是一家專業(yè)提供同心企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、HTML5、小程序制作等業(yè)務(wù)。10年已為同心眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進(jìn)行中。
準(zhǔn)備工作
首先,配置PHP.INI文件中的opcache相關(guān)參數(shù),以開(kāi)啟OPCACHE功能:
zend_extension=php_opcache.dll
[opcache]
; Determines if Zend OPCache is enabled
opcache.enable=1
; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1
; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=8
; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 100000 are allowed.
opcache.max_accelerated_files=8000
; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=0
; If disabled, all PHPDoc comments are dropped from the code to reduce the
; size of the optimized code.
opcache.save_comments=0
; Enables and sets the second level cache directory.
; It should improve performance when SHM memory is full, at server restart or
; SHM reset. The default "" disables file based caching.
opcache.file_cache=C:\MyApp\www\cache
; Enables or disables opcode caching in shared memory.
opcache.file_cache_only=0
編譯
從網(wǎng)上得到一段編譯的代碼,自己根據(jù)實(shí)際情況修改了一下,代碼如下:
isDir() && preg_match('%\.php$%', $v->getRealPath())) {
$phpFile = $v->getRealPath();
if (filesize($phpFile) > 2) {
if (opcache_compile_file($phpFile)) {
$search = $dir;
$append = str_replace(':', '', $dir);
$repl = 'C:\BeyondScreen\www\cache\\' . $cacheMd5 . '\\' . $append;
$cachePath = str_replace($search, $repl, $phpFile) . '.bin';
if (file_exists($cachePath)) {
echo "{$phpFile}\n";
file_put_contents($phpFile, ''); //清空原來(lái)的PHP腳本
}
}
}
}
}
}
上面代碼的思路是遍歷傳入的源文件目錄,對(duì)找到的PHP文件進(jìn)行編譯,然后檢查輸出路徑中是否有已經(jīng)編譯成功的文件,如果有,則把源PHP文件內(nèi)容清空,這樣服務(wù)器就會(huì)直接調(diào)用編譯后的代碼,而不是重新編譯了。
使用方法(假設(shè)上面代碼的php文件名為opcache_compile_file.php),第一個(gè)參數(shù)的值為待編譯的PHP源代碼目錄:
php opcache_compile_file.php "C:\BeyondScreen\www\byserver"
幾個(gè)問(wèn)題
在實(shí)現(xiàn)上面的PHP代碼編譯過(guò)程中,遇到了一些問(wèn)題,如下:
1、 源目錄中的文件沒(méi)有全部編譯;
我們的框架是Yii2,編譯后發(fā)現(xiàn)框架的很多代碼沒(méi)有編譯,沒(méi)有時(shí)間去查找原因,只是在編譯腳本中增加了一些邏輯,只對(duì)內(nèi)容不為空的PHP文件進(jìn)行編譯,然后編譯時(shí)執(zhí)行兩遍編譯命令來(lái)確保全部PHP文件都被編譯。
2、 部分PHP文件編譯失?。?br/>大多數(shù)問(wèn)題是XXX類已經(jīng)存在,所以編譯失敗,處理方案是編譯腳本中檢查編譯結(jié)果,對(duì)于編譯失敗的PHP文件不清空。
新聞名稱:PHP代碼編譯為OPCODE
文章鏈接:http://fisionsoft.com.cn/article/jcspdh.html