php扩展开发入门demo示例

yipeiwu_com5年前PHP代码库

本文实例讲述了php扩展开发。分享给大家供大家参考,具体如下:

一、进入php源码包,找到ext文件夹

cd /owndata/software/php-5.4.13/ext

文件夹下放的都是php的相关扩展模块

二、生成自己的扩展文件夹和相关文件

php支持开发者开发自己的扩展,提供了ext_skel骨架,用来构建扩展基本文件

./ext_skel --extname=myext

运行完成后,会在ext目录下生产一个myext扩展目录

三、编写一个hello world简单测试扩展

cd myext

1.编辑myext目录下的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])

2.编辑php_myext.h文件

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

PHP_FUNCTION(myext_helloworld);

3.编辑myext.c文件在这个里面增加一行PHP_FE(myext_helloworld,  NULL)

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[] */
};

最后在文件末尾加入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("my first ext,Hello World!\n");
  RETRUN_TRUE;
}

四、编译php扩展

在myext目录下运行phpize

/usr/local/webserver/php/bin/phpize

安装扩展

./configure --with-php-config=/usr/local/webserver/php/bin/php-config
 
make && make install

然后在php安装的目录下生产.so的文件

/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20100525/myext.so

复制myext.so文件到php安装的扩展目录下

cp myext.so /usr/local/webserver/php/ext/

编辑php.ini文件加入一行扩展路径

extension=/usr/local/webserver/php/ext/myext.so

重启php-fpm

service php restart

查看php扩展是否安装进去了

/usr/local/webserver/php/bin/php -m|grep myext

确认成功后测试myext打印helloworld

 /usr/local/webserver/php/bin/php -r "myext_helloworld('test');"

或者创建demo.php

<?php
echo myext_helloworld('test');
?>

/usr/local/webserver/php/bin/php demo.php

运行后输出

my first ext,Hello World!

自此扩展开发小demo就实现了

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP扩展开发教程》、《PHP网络编程技巧总结》、《php curl用法总结》、《PHP数组(Array)操作技巧大全》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《php字符串(string)用法总结

希望本文所述对大家PHP程序设计有所帮助。

相关文章

关于zend studio 出现乱码问题的总结

出现乱码的地方大概有4个地方:1、文件的编码方式(就是你新建文件的编码),这一点需要设置编辑器的编码方式。2、页面没有指定浏览器编码的显示方式,这一点解决的办法是:1,如果页面是.htm...

PHP session有效期问题

一个已知管用的方法是,使用session_set_save_handler,接管所有的session管理工作,一般是把session信息存储到数据库,这样可以通过SQL语句来删除所有过期...

mod_php、FastCGI、PHP-FPM等PHP运行方式对比

概述 写这篇文章的是因为今天要Ubuntu下搭建LNMP环境,Nginx使用的是PHP-FPM,所以对Web服务器与PHP解释器的交互方式做了个整理。 众所周知,PHP是跨平台、跨服务器...

php实现扫描二维码根据浏览器类型访问不同下载地址

<?php $Agent = $_SERVER['HTTP_USER_AGENT']; preg_match('/android|iphone/i',$Agent,$m...

php函数的常用方法及注意之处小结

复制代码 代码如下: <?php /** * @author Yuans * @copyright php.com * @package 函数的常用使用方法及特性. */ # 基础...