search
HomeBackend DevelopmentPHP TutorialPHP extension development series under Linux: 2. A typical extension development_PHP tutorial

After reading some of the content mentioned in the preface, you should have a general understanding of PHP extension development. Some people may think that developing extensions is troublesome and complicated. In fact, it is not. In this article, we will quickly explain Get into character and develop our first extension.


1. Compile PHP

Before development, you need to prepare the PHP source code and compile it. The process is as follows:

<span tar</span> -zxvf php-<span 5.3</span>.<span 9</span>.<span tar</span><span .gz
cd php</span>-<span 5.3</span>.<span 9</span>

I am using php5.3.9. After decompression, we entered the PHP source directory, then we directly compiled and added php.ini:

./configure --prefix=/usr/local/webserver/php --enable-fastcgi --enable-fpm --enable-<span debug
</span><span make</span> && <span make</span> <span install</span>
<span cp</span> /home/soft/php-<span 5.3</span>.<span 9</span>/php.ini-development /usr/local/webserver/php/lib/php.ini

Compilation is completed. I did not statically compile other extensions, but enabled debugging, which will be used later. Then modify the corresponding items in php.ini, which I won’t go into detail here.

Now add PHP related environment variables to save a lot of work later:

vim /root/.bash_profile

I use root, and other different users modify the .bask_profile file in the corresponding user directory, and add: /usr/local/webserver/php/bin/ after the PATH in the file, similar to the following:

PATH=$PATH:$HOME/bin:/usr/local/webserver/php/bin/

Environment variables are set, let’s check the PHP version:

OK, the compilation is completed, let us continue.

2. Typical development process

A typical extension development process is as follows:

3. Extended function definition

-2147483648 to 2147483647, same as 32-bit systems.

4. Formal development

cd /home/soft/php-<span 5.3</span>.<span 9</span>/ext

Then learn about the extended skeleton tool ext_skel provided by PHP to generate a skeleton. The usage of ext_skel is as follows:

./ext_skel --extname=module [--proto=<span file</span>] [--stubs=<span file</span>] [--xml[=<span file</span><span ]]
           [</span>--skel=<span dir</span>] [--full-xml] [--no-<span help]

  </span>--extname=<span module   module is the name of your extension(模块名,会在当前目录创建一个该名称子目录)
  </span>--proto=<span file</span>       <span file</span><span  contains prototypes of functions to create(函数原型定义文件)
  </span>--stubs=<span file</span>       generate only <span function</span> stubs <span in</span> <span file</span>
  --xml              generate xml documentation to be added to phpdoc-<span cvs
  </span>--skel=<span dir</span>         path to the skeleton directory(设置骨架生成的目录,不设置该项则默认在ext/<span extname下)
  </span>--full-xml         generate xml documentation <span for</span> a self-<span contained extension
                     (not yet implemented)
  </span>--no-help          don<span '</span><span t try to be nice and create comments in the code</span>
                     and helper functions to test <span if</span> the module compiled (生成的代码中不显示各种帮助注释)

This time we are going to use two options, --extname=myip is to define the name of the extension, and --proto=myip.pro is to define the function prototype of the extension. First we generate the extension function prototype file:

vim myip.pro

Add the following:

<span int</span> ip2long32(<span string</span> ip)

This means that there is a function in our extension that returns an int and takes a string as input.

At this time, execute the following command to generate the extended skeleton:

./ext_skel --extname=myip --proto=myip.pro

OK, at this time you will find that a subdirectory myip is generated under the current PHP extension directory. Enter myip and take a look:

<span cd myip
ll</span>

You will find a bunch of files generated, as shown below:

At this point we can proceed to the second step.

2. Modify config.m4

Regarding the function of the config.m4 file, we will leave it to a later article to explain in detail. Now we only explain what to do.

Use vim to edit config.m4:

vim config.m4

Remove the dnl at the beginning of lines 16 to 18, as follows:

The specific reasons for doing this will be explained in a later article. Here we directly exit and save config.m4 and continue to the next step.

3. Encoding

The main event is here, you can finally enter myip.c to code functions, let’s cheer together!

vim myip.c

Find the location shown in the picture below:

The picture shows the corresponding function generated by the extended skeleton tool based on the function prototype we provided. There are several things to note here:

1. PHP_FUNCTION: It is a macro defined by PHP core. It is the same as ZEND_FUNCTION and is used to define extension functions. The actual generated function name is zif_ip2long32.

2. zend_parse_parameters: Since PHP is a weakly typed language and C is a strongly typed language, this function needs to be used to receive the parameters passed in by PHP and perform certain type conversions to convert PHP variables into C language. Type of identification.

The prototype of zend_parse_parameters function is as follows:

zend_parse_parameters(<span int</span> num_args TSRMLS_CC, <span char</span> *type_spec, &hellip;);

Parameter description:

  •       num_args:传递给函数的参数个数。通常的做法是使用宏 ZEND_NUM_ARGS()。
  •       TSRMLS_CC:线程安全,总是传递TSRMLS_CC宏。 详解:http://www.54chen.com/php-tech/what-is-tsrmls_cc.html
  •       type_spec:第三个参数是一个字符串,指定了函数期望的参数类型
  •       ...:需要随参数值更新的变量列表]

  • type_spec是格式化字符串,其常见的含义如下: 参数   代表着的类型 b   Boolean l   Integer 整型 d   Floating point 浮点型 s   String 字符串 r   Resource 资源 a   Array 数组 o   Object instance 对象 O   Object instance of a specified type 特定类型的对象 z   Non-specific zval 任意类型~ Z   zval**类型 f   表示函数、方法名称

   我们将该函数修改为如下内容:

<span  PHP_FUNCTION(ip2long32)
 {
         </span><span char</span> *ip =<span  NULL;
         </span><span int</span> argc =<span  ZEND_NUM_ARGS();
         </span><span int</span><span  ip_len;
 
         </span><span if</span> (zend_parse_parameters(argc TSRMLS_CC, <span "</span><span s</span><span "</span>, &ip, &ip_len) ==<span  FAILURE) {
                 </span><span return</span><span ;
         }
         
         int32_t ip_int32;
         unsigned </span><span char</span><span  ip1, ip2, ip3, ip4;
         
         sscanf(ip, </span><span "</span><span %hhu.%hhu.%hhu.%hhu</span><span "</span>, &ip1, &ip2, &ip3, &<span ip4);
         ip_int32 </span>= (int32_t)((ip1 << <span 24</span>) | (ip2 << <span 16</span>) | (ip3 << <span 8</span>) |<span  ip4);
         RETURN_LONG(ip_int32);
 }</span>

    功能完成了,这边有个RETURN_LONG(ip_int32)比较特殊,这也是PHP内核提供的宏,用于返回值给PHP,具体说明如下:

设置返回值并且结束函数        设置返回值             宏返回类型和参数
RETURN_LONG(l)           RETVAL_LONG(l)           整数
RETURN_BOOL(b)          RETVAL_BOOL(b)           布尔数(1或0)
RETURN_NULL()           RETVAL_NULL()           NULL
RETURN_DOUBLE(d)        RETVAL_DOUBLE(d)        浮点数
RETURN_STRING(s, dup)       RETVAL_STRING(s, dup)       字符串。如果dup为1,引擎会调用estrdup()重复s,使用拷贝。如果dup为0,就使用s
RETURN_STRINGL(s, l, dup)     RETVAL_STRINGL(s, l, dup)    长度为l的字符串值。与上一个宏一样,但因为s的长度被指定,所以速度更快。
RETURN_TRUE           RETVAL_TRUE            返回布尔值true。注意到这个宏没有括号。
RETURN_FALSE           RETVAL_FALSE           返回布尔值false。注意到这个宏没有括号。
RETURN_RESOURCE(r)        RETVAL_RESOURCE(r)       资源句柄。

    编码完成了,保存并退出,然后我们可以开始编译了。

    4. 编译

<span phpize
.</span>/configure --with-php-config=/usr/local/webserver/php/bin/php-<span config
</span><span make</span> && <span make</span> <span install</span>

    不出意外的话编译完成后会有如下提示:

Installing shared extensions:     /usr/local/webserver/php/lib/php/extensions/debug-non-zts-<span 20090626</span>/

    进入该目录看下是否已经有myip.so,有的话最后我们就可以修改php.ini载入该so文件

    5. 修改php.ini

cd /usr/local/webserver/php/<span lib
vim php.ini</span>

    修改extension_dir,并加入 extension = myip.so

extension_dir = "/usr/local/webserver/php/lib/php/extensions/debug-non-zts-20090626/"<span 
extension </span>= myip.so

    退出保存,并重启php,如果是使用Phpfpm的话可以执行如下命令:

<span kill</span> -USR2 `<span cat</span> /usr/local/webserver/php/var/run/php-fpm.pid`

    看下扩展是否正常载入:

[root@tm977 lib]# php -m|<span grep</span><span  myip
myip</span>

    说明已经正常载入了,最后我们测试下扩展函数吧!

    6. 测试

php -r <span "</span><span var_dump(ip2long32('192.168.1.1'));</span><span "</span>
<span int</span>(-<span 1062731519</span><span )
php </span>-r <span "</span><span var_dump(ip2long('192.168.1.1'));</span><span "</span>  
<span int</span>(<span 3232235777</span>)

    如上所示,ip2long32输出的是32位有符号整数,而ip2long输出的是64位无符号整数,大功告成!

 

五、小结

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440319.htmlTechArticleAfter reading some of the content mentioned in the preface, you should have a general understanding of PHP extension development. Some people may think that developing extensions is troublesome and complicated. In fact, it is not. This...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
什么是linux设备节点什么是linux设备节点Apr 18, 2022 pm 08:10 PM

linux设备节点是应用程序和设备驱动程序沟通的一个桥梁;设备节点被创建在“/dev”,是连接内核与用户层的枢纽,相当于硬盘的inode一样的东西,记录了硬件设备的位置和信息。设备节点使用户可以与内核进行硬件的沟通,读写设备以及其他的操作。

Linux中open和fopen的区别有哪些Linux中open和fopen的区别有哪些Apr 29, 2022 pm 06:57 PM

区别:1、open是UNIX系统调用函数,而fopen是ANSIC标准中的C语言库函数;2、open的移植性没fopen好;3、fopen只能操纵普通正规文件,而open可以操作普通文件、网络套接字等;4、open无缓冲,fopen有缓冲。

linux中什么叫端口映射linux中什么叫端口映射May 09, 2022 pm 01:49 PM

端口映射又称端口转发,是指将外部主机的IP地址的端口映射到Intranet中的一台计算机,当用户访问外网IP的这个端口时,服务器自动将请求映射到对应局域网内部的机器上;可以通过使用动态或固定的公共网络IP路由ADSL宽带路由器来实现。

什么是linux交叉编译什么是linux交叉编译Apr 29, 2022 pm 06:47 PM

在linux中,交叉编译是指在一个平台上生成另一个平台上的可执行代码,即编译源代码的平台和执行源代码编译后程序的平台是两个不同的平台。使用交叉编译的原因:1、目标系统没有能力在其上进行本地编译;2、有能力进行源代码编译的平台与目标平台不同。

linux中eof是什么linux中eof是什么May 07, 2022 pm 04:26 PM

在linux中,eof是自定义终止符,是“END Of File”的缩写;因为是自定义的终止符,所以eof就不是固定的,可以随意的设置别名,linux中按“ctrl+d”就代表eof,eof一般会配合cat命令用于多行文本输出,指文件末尾。

linux怎么查询mac地址linux怎么查询mac地址Apr 24, 2022 pm 08:01 PM

linux查询mac地址的方法:1、打开系统,在桌面中点击鼠标右键,选择“打开终端”;2、在终端中,执行“ifconfig”命令,查看输出结果,在输出信息第四行中紧跟“ether”单词后的字符串就是mac地址。

linux怎么判断pcre是否安装linux怎么判断pcre是否安装May 09, 2022 pm 04:14 PM

在linux中,可以利用“rpm -qa pcre”命令判断pcre是否安装;rpm命令专门用于管理各项套件,使用该命令后,若结果中出现pcre的版本信息,则表示pcre已经安装,若没有出现版本信息,则表示没有安装pcre。

linux中rpc是什么意思linux中rpc是什么意思May 07, 2022 pm 04:48 PM

在linux中,rpc是远程过程调用的意思,是Reomote Procedure Call的缩写,特指一种隐藏了过程调用时实际通信细节的IPC方法;linux中通过RPC可以充分利用非共享内存的多处理器环境,提高系统资源的利用率。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor