Just in the PHP group and everyone chat, promised to write an article on how to implement the PHP source code encryption, by this will be the opportunity of QA in smoke, on this issue, I write some ideas.
As my previous article has introduced, ZE (Zend engine) executes a PHP script that undergoes compilation-> execution, except that it compiles PHP files every time it executes. Compilation and execution separation is not implemented.
There are two important functions in Ze's compilation and execution phase:
Zend_api Zend_op_array * (*zend_compile_file) (zend_file_handle *file_handle, int type TSRMLS_DC);
And
Zend_api void (*zend_execute) (Zend_op_array *op_array tsrmls_dc);
Zend_compile_file is responsible for compiling the script file to be executed into the OP codes composed of Ze's basic instruction sequence, and then handing the OP codes to the Zend_execute execution to get the result of our script.
Therefore, we can completely modify the default Zend_complie_file and Zend_execute to achieve, PHP execution and compiler separation, further, we can also be implemented on this basis, the encryption and decryption of our scripts.
We implement this function through a php extension module, first of all, we need to initialize the module at the time:
PHP_MINIT_FUNCTION(sample)
{
old_compile_file = zend_compile_file; //保存现场
old_execute = zend_execute;
zend_compile_file = my_compile_file; //截获
zend_execute = my_execute;
return SUCCESS;
}
In our my_compile_file, we judge whether our file is a compiled file, assuming that the suffix name is *.ze.
static zend_op_array *my_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
if(strstr(file_handle->filename, ".ze") != NULL){//是编译过的文件。
直接返回文件内容.
}
zend_op_array *op_array;
op_array = old_compile_file (file_handle, type TSRMLS_CC); //调用默认的compile,截获输出
if(op_array){
保存op_array;
}
return op_array;
}