centos php扩展开发流程

一、安装php

  centos 默认 yum 安装 php 版本为 5.3, 很多php框架基本上要求5.4以上版本,这时候不能直接 用 yum install php 需要先改yum 源。

1、启动REMI源

1 # cd /tmp

2 # wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
 
3 # wget http://mirrors.sohu.com/fedora-epel/6/i386/epel-release-6-8.noarch.rpm

2、rpm安装

# rpm -Uvh remi-release-6.rpm epel-release-6-8.noarch.rpm

3、安装 >=5.4以上php

# yum --enablerepo=remi install php  

二、扩展开发

1、php源码下载

# wget http://cn2.php.net/distributions/php-5.4.43.tar.gz
# tar vzxf php-5.4.42.tar.gz

注意这里下载的版本要跟系统安装的php版本保持一致,php查看咱在版本命令

php -v

我系统安装是5.4 的

2、安装phpize

(phpize是用来扩展php扩展模块的,通过phpize可以建立php的外挂模块)

# yum install phpize

3、ext_skel工具 

ext_skel 是php写扩展提供一个很好用的 “自动构建系统” 使用他可以方便的搭建php扩展。 此工具为php源码自带工具位于 源码里头的 ext目录下

# cd /php-5.4.43/ext

# ./ext_skel --extname = myext

执行生成扩展后 ext 下面会自动多一个 myext文件夹

# cd  myext
# vim config.m4

将 config.m4文件里面

dnl PHP_ARG_WITH(myext, for myext support,
dnl Make sure that the comment is aligned:
dnl [  --with-myext             Include myext support])

修改成

PHP_ARG_WITH(myext, for myext support,
[  --with-myext             Include myext support])

4、写简单的测试c扩展

修改php_myext.h,看到PHP_FUNCTION(confirm_myext_compiled); 这里就是扩展函数声明部分,可以增加一

PHP_FUNCTION(confirm_myext_compiled);

PHP_FUNCTION(myext_helloworld);


然后修改myext.c,这个是扩展函数的实现部分。

const zend_function_entry myext_functions[] = {
        PHP_FE(confirm_myext_compiled,  NULL)           /* For testing, remove later. */
        PHP_FE(myext_helloworld,  NULL)
        PHP_FE_END      /* Must be the last line in myext_functions[] */
};

这的代码是将函数指针注册到Zend引擎,增加一行PHP_FE(myext_helloworld,  NULL)(后面不要带分号)。

在myext.c末尾加myext_helloworld的执行代码。

PHP_FUNCTION(myext_helloworld)
{
        char *arg = NULL;
    int arg_len, len;
    char *strg;
    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &arg, &arg_len) == FAILURE) {
        return;
    }
    php_printf("Hello World!
");
    RETRUN_TRUE;
}

zend_parse_parameters是用来接受PHP传入的参数,RETURN_XXX宏是用来返回给PHP数据。

5、编译安装php扩展

# phpize
# ./configure
# make
# make test
# make install

跳到php扩展文件加里头可以看到多了个myext.so 文件

# cd /usr/lib64/php/modules
# vim /etc/php.ini

添加一行扩展

extension=myext.so

查看扩展是否安装成功

php -m

看到多了个myext.so扩展,ok大功告成,接下来我们这看下我们自定义的函数能否正确执行


执行php -r “myext_helloworld(‘test’);”,输出hello world!

三、小小感悟

echosong 以前在window下做php扩展 各种问题各种不顺,最新发现liunx 下做php扩展比window方便很多。如果想做php扩展的朋友们建议直接上手liunx下开发。

另外感觉liunx c 的开发 ,特别跟操作系统的沟通 各种顺畅。O(∩_∩)O~

原文地址:https://www.cnblogs.com/echosong/p/4639062.html