PHP 扩展开发(一)

本文详细介绍如何从零开始创建并编译一个PHP扩展。包括下载PHP源代码、使用ext_skel脚手架生成扩展模板、修改配置文件以启用扩展、编写扩展函数及编译安装过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

准备工作
根据自己开发的扩展需要应用的php版本,去下载对应的php源代码。下载地址, 下载完毕后,解压缩。开发是在linux环境,php版本是5.5。
开始开发
打开源代码目录,进入ext目录内
cd php-5.5.38/ext
执行如下命令,生成扩展的原始文件
./ext_skel --extname=helloWord
可以看到ext目录下生成了helloWord文件夹,进入helloWord,然后查看生成的文件
cd helloWord
ls -l
total 32
-rw-r--r-- 1 spring spring 2146 May 26 19:28 config.m4
-rw-r--r-- 1 spring spring  317 May 26 19:28 config.w32
-rw-r--r-- 1 spring spring    9 May 26 19:28 CREDITS
-rw-r--r-- 1 spring spring    0 May 26 19:28 EXPERIMENTAL
-rw-r--r-- 1 spring spring 5254 May 26 19:28 helloWord.c
-rw-r--r-- 1 spring spring  511 May 26 19:28 helloWord.php
-rw-r--r-- 1 spring spring 2937 May 26 19:28 php_helloWord.h
drwxr-xr-x 2 spring spring 4096 May 26 19:28 tests
修改config.m4文件,
sudo vim config.m4  
把代码
dnl PHP_ARG_WITH(helloWord, for helloWord support,
dnl Make sure that the comment is aligned:
dnl [  --with-helloWord             Include helloWord support])
修改成
PHP_ARG_WITH(helloWord, whether to enable helloWord support,
Make sure that the comment is aligned:
[  --enable-helloWord           Enable helloWord support])
这个配置是./configure时能够调用enable-sample选项的最低要求.PHP_ARG_WITH的第二个参数将在./configure处理过程中到达这个扩展的配置文件时显示. 第三个参数将在终端用户执行./configure –help时显示为帮助信息.
修改 php_helloWord.h
PHP_FUNCTION(confirm_helloWord_compiled);
修改成
PHP_FUNCTION(helloWord);
修改helloWord.c
把代码
const zend_function_entry helloWord_functions[] = {
        PHP_FE(confirm_helloWord_compiled,      NULL)           /* For testing, remove later. */
        PHP_FE_END      /* Must be the last line in helloWord_functions[] */
};

PHP_FUNCTION(confirm_helloWord_compiled)
{
        char *arg = NULL;
        int arg_len, len;
        char *strg;

        if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
                return;
        }

        len = spprintf(&strg, 0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "helloWord", arg);
        RETURN_STRINGL(strg, len, 0);
}

修改成
const zend_function_entry helloWord_functions[] = {
        PHP_FE(helloWord,       NULL)           /* For testing, remove later. */
        PHP_FE_END      /* Must be the last line in helloWord_functions[] */
};

PHP_FUNCTION(array_square_sum)
{
        php_printf("Hello World!\n");
        RETURN_TRUE;
}
生成configure文件
phpize
可以看出helloWord文件夹中生成了configure文件
生成扩展
./configure
make
可以看到在modules文件夹下生成了.so文件
cd modules
ls
helloWord.la  helloWord.so
把so文件放到php扩展目录里面,修改php.ini文件,重启php_fpm, nginx 就可以使用这个函数了。
参考文档

一步一步入门编写PHP扩展

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值