PHP扩展

#cd /php/ext/

#./ext_skel --extname=myext

1. $ cd ..
2. $ vi ext/myext/config.m4
3. $ ./buildconf
4. $ ./configure --[with|enable]-myext
5. $ make
6. $ ./sapi/cli/php -f ext/myext/myext.php
7. $ vi ext/myext/myext.c
8. $ make

Repeat steps 3-6 until you are satisfied with ext/sylar/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.

修改config.m4

#vim config.m4

dnl PHP_ARG_ENABLE(myextensions , whether to enable myextensions support,

dnl Make sure that the comment is aligned:

dnl [  --enable-myextensions            Enable myextensions support])

修改为:

PHP_ARG_ENABLE(myextensions , whether to enable myextensions support,

Make sure that the comment is aligned:

[  --enable-myextensions            Enable myextensions support])

修改php_myext.h

找到PHP_FUNCTION(confirm_myext_compiled);在后面新增一行:

PHP_FUNCTION(myext);

修改myext.c

a.找到

PHP_FE(confirm_myext_compiled,      NULL) /* For testing, remove later. */】

在后面添加一行:

PHP_FE(myext, NULL)

b.在文件最末尾增加如下代码:

PHP_FUNCTION(myext)

{

char *arg = NULL;

int arg_len, len;

char *strg;

if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, “s”, &arg, &arg_len) == FAILURE) {

return;

}

// Your code here....

//len = spprintf(&strg, 0, “Your input string:%s ”, arg);

//RETURN_STRINGL(strg, len, 0);

}

>>回到php根目录,执行

#./buildconf
#./configure --enable-myext
#make

或者:

>>进入扩展文件夹里,执行

#phpize // 找不到用 find / -name phpize 完整路径调用

Configuring for:

PHP Api Version:         20131106

Zend Module Api No:      20131226

Zend Extension Api No:   220131226

#./configure --with-php-config=/usr/local/php/bin/php-config // php-config对应目录
#make
#make install // 显示 /usr/local/php/lib/php/extensions/no-debug-zts-20131226/

添加扩展到php.ini中

#vim /etc/php.ini

末尾增加一行:

extension=myext.so

如果路径找不到,可以在php.ini中增加一行:

extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226" // 路径自行修改

检查安装结果:

#/usr/local/php/bin/php -m

会打印php已加载的模块:

[PHP Modules]

...

myext

...

[Zend Modules]

如能看到myext,则此php扩展已成功加载

测试php扩展

编写一个test.php

如:

<?php

  ...

>

在php根目录下运行

./php -q test.php

输出内容可以检查是否正确加载。

原文地址:https://www.cnblogs.com/sylar-liang/p/4579516.html