如何利用C自訂實現PHP擴充
由於有一部分代碼需要加解密,所以需要擴充PHP模組,於是簡單的使用base64來實現簡單的密碼編譯演算法。因為時間的關係,這裡主要是對如何?PHP擴充做一個概述和記錄,並不涉及到密碼編譯演算法的具體實現,等有空再補上。
1、環境:
centos 5
php 5.1.6
autoconf 2.59
automake 1.96
libtool
bison
flex
re2c
2、建立模組
2.1 轉到php源碼目錄擴充包目錄下
cd /usr/include/php/ext
2.2 建立一個叫做itbeing的檔案夾(這裡我們的模組名稱就叫做itbeing了)
mkdir itbeing
cd itbeing
2.3 建立config.m4檔案,config.m4 檔案使用 GNU autoconf 文法編寫,該檔案的主要作用是 檔案告訴系統構建系統哪些擴充 configure 選項是支援的,你需要哪些擴充庫,以及哪些源檔案要編譯成它的一部分。
- PHP_ARG_ENABLE(itbeing,
- ?? ? ? ?[Whether to enable the "itbeing" extension],
- ?? ? ? ?[? --enable-itbeing? ? ? ?Enable "itbeing" extension support])
- ?
- if test $PHP_ITBEING != "no"; then
- ?? ? ? ?PHP_SUBST(ITBEING_SHARED_LIBADD)
- ?? ? ? ?PHP_NEW_EXTENSION(itbeing, itbeing.c, $ext_shared)
- fi
2.4 建立php_itbeing.h 標頭檔
- #ifndef PHP_ITBEING_H
- /* Prevent double inclusion */
- #define PHP_ITBEING_H
- ?
- /* Define extension properties */
- #define PHP_ITBEING_EXTNAME "itbeing"
- #define PHP_ITBEING_EXTVER "1.0"
- ?
- /* Import configure options
- ?* when building outside of the
- ?* PHP source tree */
- #ifdef HAVE_CONFIG_H
- #include "config.h"
- #endif
- ?
- /* Include PHP standard Header */
- #include "php.h"
- /*
- ?* define the entry point symbole
- ?* Zend will use when loading this module
- ?*/
- extern zend_module_entry itbeing_module_entry;
- #define phpext_itbeing_ptr &itbeing_module_entry
- ?
- #endif /* PHP_ITBEING_H */
2.5 建立itbeing.c 檔案
- #include "php_itbeing.h"
- ?
- PHP_FUNCTION(itbeing_sayhi)
- {
- ?? ? ? ?char *name;
- ?? ? ? ?int name_len;
- ?
- ?? ? ? ?if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
- ?? ? ? ? ? ? ? ?&name, &name_len) == FAILURE)
- ?? ? ? ?{
- ?? ? ? ? ? ? ? ?RETURN_NULL();
- ?? ? ? ?}
- ?
- ?? ? ? ?php_printf("Hi, ");
- ?? ? ? ?PHPWRITE(name, name_len);
- ?? ? ? ?php_printf("!\n");
- }
- ?
- static function_entry php_itbeing_functions[] = {
- ?? ? ? ?PHP_FE(itbeing_sayhi, NULL)
- ?? ? ? ?{ NULL, NULL, NULL }
- };
- ?
- zend_module_entry itbeing_module_entry = {
- #if ZEND_MODULE_API_NO >= 20010901
- ?? ? ? ?STANDARD_MODULE_HEADER,
- #endif
- ?? ? ? ?PHP_ITBEING_EXTNAME,
- ?? ? ? ?php_itbeing_functions, /* Functions */
- ?? ? ? ?NULL, /* MINIT */
- ?? ? ? ?NULL, /* MSHUTDOWN */
- ?? ? ? ?NULL, /* RINIT */
- ?? ? ? ?NULL, /* RSHUTDOWN */
- ?? ? ? ?NULL, /* MINFO */
- #if ZEND_MODULE_API_NO >= 20010901
- ?? ? ? ?PHP_ITBEING_EXTVER,
- #endif
- ?? ? ? ?STANDARD_MODULE_PROPERTIES
- };
- ?
- #ifdef COMPILE_DL_ITBEING
- ZEND_GET_MODULE(itbeing)
- #endif
3、編譯模組
3.1 phpize
3.2 ./config -enable-itbeing
3.3 make
3.4 cp modules/itbeing.so /usr/lib/php/modules
3.5 vim /etc/php.ini 添加extension = itbeing.so
測試:php -r “itbeing_sayhi(’kokko’)”
結果:Hi,kokko
?
原文:http://www.kokkowon.com/archives/981