开发的第一个PHP扩展
下载php源码php-5.4.23.tar.gz,解压,进入/home/hubo/php-5.4.23/ext/扩展目录
wget http://cn2.php.net/get/php-5.4.23.tar.gz/from/this/mirror
tar -xzvf php-5.4.23.tar.gz
cd php-5.4.23/ext/
在ext目录中新建config.m4文件
PHP_ARG_ENABLE(heiyoubo, [Whether to enable the "heiyoubo" extension], [ enable-heiyoubo Enable "heiyoubo" extension support]) if test $PHP_HEIYOUBO != "no"; then PHP_SUBST(HEIYOUBO_SHARED_LIBADD) PHP_NEW_EXTENSION(heiyoubo, heiyoubo.c, $ext_shared) fi
在ext目录中新建heiyoubo.c文件
#ifdef HAVE_CONFIG_H #include "config.h" #endif //加载php头文件 #include "php.h" #define phpext_heiyoubo_ptr &heiyoubo_module_entry ZEND_FUNCTION(heiyoubo_hello) { php_printf("Hello World Heiyoubo!\n"); } static zend_function_entry heiyoubo_functions[] = { ZEND_FE(heiyoubo_hello, NULL) { NULL, NULL, NULL } }; //module entry zend_module_entry heiyoubo_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif "heiyoubo", //这个地方是扩展名称,往往我们会在这个地方使用一个宏。 heiyoubo_functions, /* Functions */ NULL, /* MINIT */ NULL, /* MSHUTDOWN */ NULL, /* RINIT */ NULL, /* RSHUTDOWN */ NULL, /* MINFO */ #if ZEND_MODULE_API_NO >= 20010901 "2.1", //这个地方是我们扩展的版本 #endif STANDARD_MODULE_PROPERTIES }; #ifdef COMPILE_DL_HEIYOUBO ZEND_GET_MODULE(heiyoubo) #endif
运行phpize,准备 PHP 扩展库的编译环境
[hubo@test15169x ~/php-5.4.23/ext]$ /usr/local/php/bin/phpize
Configuring for:
PHP Api Version: 20100412
Zend Module Api No: 20100525
Zend Extension Api No: 220100525
configure的时候要开启heiyoubo扩展,并且指定php-config的目录,获取所安装的 PHP 配置的信息
[hubo@test15169x ~/php-5.4.23/ext]$ ./configure --enable-heiyoubo --with-php-config=/usr/local/php/bin/php-config
[hubo@test15169x ~/php-5.4.23/ext]$ make
[hubo@test15169x ~/php-5.4.23/ext]$ make test
heiyoubo.so扩展已经生成到module目录
[hubo@test15169x ~/php-5.4.23/ext]$ ll modules/*
-rw-rw-r-- 1 hubo hubo 799 01-09 16:53 modules/heiyoubo.la
-rwxrwxr-x 1 hubo hubo 26K 01-09 16:53 modules/heiyoubo.so
将heiyoubo.so文件拷贝到php的扩展目录
[hubo@test15169x ~/php-5.4.23/ext]$ php -ini | grep extension_dir
extension_dir => /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525 => /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525
[hubo@test15169x ~/php-5.4.23/ext]$ cp modules/heiyoubo.so /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/
将heiyoubo.so加到php的扩展文件/usr/local/etc/cgi/php.ini中 extension = "heiyoubo.so"
[hubo@test15169x ~/php-5.4.23/ext]$ php --ini
Configuration File (php.ini) Path: /usr/local/etc/cgi
Loaded Configuration File: /usr/local/etc/cgi/php.ini
[hubo@test15169x ~/php-5.4.23/ext]$ php -r 'var_dump(get_loaded_extensions());' | grep heiyoubo
string(8) "heiyoubo"
验证安装成功。执行C扩展中函数heiyoubo_hello();执行成功
[hubo@test15169x ~/php-5.4.23/ext]$ php -r 'heiyoubo_hello();'
Hello World Heiyoubo!
参考链接:
http://www.php.net/manual/zh/internals2.buildsys.configunix.php
https://github.com/walu/phpbook/blob/master/5.1.md 《Extending and Embedding PHP》中文版翻译 PHP扩展开发及内核应用