博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PHP代码编译为OPCODE
阅读量:7111 次
发布时间:2019-06-28

本文共 2473 字,大约阅读时间需要 8 分钟。

简介

OPCODE是PHP编译后的二进制代码,生成的Opcode作为一种中间语言,可以帮助实现PHP源程序代码的不开源,当然,这种代码也很容易被反编译,不过对于一些简单的场景也是很足够了。

编译的基本思路是首先在php.ini中配置加载opcache扩展,并配置相关参数,然后执行一个PHP脚本遍历源代码目录,并进行编译,核心的函数是opcache_compile_file(),该函数会根据php.ini中的参数,编译并输出二进制代码。

准备工作

首先,配置PHP.INI文件中的opcache相关参数,以开启OPCACHE功能:

zend_extension=php_opcache.dll[opcache]; Determines if Zend OPCache is enabledopcache.enable=1; Determines if Zend OPCache is enabled for the CLI version of PHPopcache.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

编译

从网上得到一段编译的代码,自己根据实际情况修改了一下,代码如下:

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, ''); //清空原来的PHP脚本 } } } } }}

上面代码的思路是遍历传入的源文件目录,对找到的PHP文件进行编译,然后检查输出路径中是否有已经编译成功的文件,如果有,则把源PHP文件内容清空,这样服务器就会直接调用编译后的代码,而不是重新编译了。

使用方法(假设上面代码的php文件名为opcache_compile_file.php),第一个参数的值为待编译的PHP源代码目录:

php opcache_compile_file.php "C:\BeyondScreen\www\byserver"

几个问题

在实现上面的PHP代码编译过程中,遇到了一些问题,如下:

1、 源目录中的文件没有全部编译;
我们的框架是Yii2,编译后发现框架的很多代码没有编译,没有时间去查找原因,只是在编译脚本中增加了一些逻辑,只对内容不为空的PHP文件进行编译,然后编译时执行两遍编译命令来确保全部PHP文件都被编译。
2、 部分PHP文件编译失败;
大多数问题是XXX类已经存在,所以编译失败,处理方案是编译脚本中检查编译结果,对于编译失败的PHP文件不清空。

转载于:https://blog.51cto.com/lancelot/2083165

你可能感兴趣的文章
css垂直居中
查看>>
单元测试
查看>>
ASP.NET 开源 Blog 收集
查看>>
【java IO File】统计项目代码总共多少行
查看>>
vmware12中安装MAC OS X 10.10
查看>>
placeholder样式
查看>>
读书笔记之_Win10 与Jmeter5.1.1界面兼容:
查看>>
suse10安装oracle11g出现的问题解决
查看>>
js与php传递参数
查看>>
[转]DPM2012系列之六:在Win7上安装DPM远程管理控制台
查看>>
MSSQL清理日志
查看>>
Class hierarchy of UIResponder as well as subclasses of UIView and UIControl
查看>>
IntelliJ IDEA + Maven环境编写第一个hadoop程序
查看>>
OpenGL应用函数库介绍
查看>>
常量、枚举
查看>>
条件变量与互斥量
查看>>
Jenkins-Publish HTML reports
查看>>
KVO 键值观察
查看>>
iOS开发网络篇—发送GET和POST请求(使用NSURLSession)
查看>>
Adaptability Is Accessibility
查看>>