search
HomeBackend DevelopmentPHP TutorialPHP扩展开发(1):入门

有关PHP扩展开发的文章、博客已经很多了,比较经典的有:

  1. TIPI项目(http://www.php-internals.com/,强烈推荐)
  2. 《Extending and Embedding PHP》(中文翻译见http://www.walu.cc/phpbook/,强烈推荐)
  3. 《PHP核心技术与最佳实践》一书有一章专门讲PHP扩展开发的,不过版本较老,可供参考。
  4. 《PHP5权威指南》一书中也有一章专门讲到了PHP的扩展开发。

我准备在此系列博文中总结我有关PHP扩展开发的学习和感悟,力图简单清晰地描述在Linux系统下开发一个PHP扩展应该具备的最基本知识。水平较低,难免有错误,望指出。

 

 

准备工作

首先要获取一份PHP源码(可以从Github上签出,或者到官网上下载最新的稳定版),然后编译之。为了加快编译速度,我们推荐禁用所有额外的扩展(使用--disable-all选项),但最好打开debug(使用--enable-debug选项)和线程安全(使用--enable-maintainer-zts),但要在发布扩展的时候关闭debug,视情况选择是否需要打开线程安全:

$ ./buildconf --force$ ./configure --disable-all --enable-debug --enable-maintainer-zts$ make

注意,我们没有指定--prefix选项(同时也没有make install),因为这不是必须的。注意查看输出信息,也许你需要安装一些依赖包才能成功编译PHP。

编译后的PHP的可执行程序在源码的sapi目录下,对应不同的宿主环境有不同的子目录,我们以后都主要使用cli(command line interface)环境,可以建一个别名方便引用:

$ alias php-dev=/usr/local/src/php-5.6.5/sapi/cli/php

有一些命令行选项是很有用的:

php-dev -h          # 打印帮助信息php-dev -v          # 打印版本信息php-dev --ini        # 打印配置信息        php-dev -m          # 打印加载的模块信息php-dev -i          # phpinfophp-dev -r <code>      # 执行code里的代码

 

 

扩展骨架

PHP的所有官方扩展都在源码的ext目录下,我们自己写的扩展也可以放在该目录下。注意,该目录下有个名为ext_skel的shell脚本,它是用来生成PHP扩展骨架的,使用该脚本,可以帮我们快速创建PHP扩展:

$ ./ext_skel --extname=myext

上面的命令帮我们创建了一个名为myext的扩展,源码在myext目录下。不带任何参数的执行该脚本可以打印帮助信息,这样你可以查看到该脚本提供的更多选项。

接下来让我们完成我们的扩展。进入myext目录,编辑config.m4配置文件,找到PHP_ARG_ENABLE宏函数,去掉前面的dnl注释(共三行)。退回到源码根目录,重新执行buildconf、configure和make命令:

$ ./buildconf --force$ ./configure --help | grep myext    --enable-myext           Enable myext support$ ./configure --disable-all --enable-myext --enable-debug --enable-maintainer-zts$ make

注意,我们用./configure --help | grep myext打印了我们扩展的加载情况,如果看不到下面的输出,则说明我们的扩展没有配置成功,回头检查下config.m4文件。

这次编译应该非常快,因为大部分代码都已经编译过了。PHP还有另外一种编译扩展的方法(使用动态连接的方式,将扩展编译为.so的文件),不过我们推荐在开发扩展的时候使用静态编译,因为这样省去了在配置文件中加载扩展的步骤。

一切顺利的话,我们的第一个扩展就已经可以执行了:

$ php-dev -m | grep myextmyext$ php-dev -r 'echo confirm_myext_compiled("myext") . "\n";'Congratulations! You have successfully modified ext/myext/config.m4. Module myext is now compiled into PHP.

第一个命令显示了我们的扩展已经被加载。第二个命令执行了ext_skel扩展骨架自动为我们创建的函数。当然,这个函数毫无意义,不过我们可以很容易的把这个函数改编成hello world。

 

 

手动创建扩展

大部分教程都是以ext_skel扩展骨架为原型讲述扩展开发的,这种做法当然很方便快捷。但是我个人更喜欢纯手工开发扩展的方式,因为这样更容易理解其中的每一个细节。

手动创建扩展,先进入ext目录,创建我们的扩展目录myext2。有几个文件是必须的:config.m4,myext2.c和php_myext2.h。

首先,我们来编写配置文件config.m4:

PHP_ARG_ENABLE(myext2, whether to enable myext2 support,[  --enable-myext2           Enable myext2 support])if test "PHP_MYEXT2" != "no"; then   PHP_NEW_EXTENSION(myext2, myext2.c, $ext_shared)fi

config.m4其实是autoconf程序使用的配置文件,autoconf是autotools工具箱里重要的组成。完整介绍autoconf的用法是需要很长时间的,好在我们这里的用法非常简单。

PHP_ARG_ENABLE是PHP为autoconf定义的宏函数,myext2是它的第一个参数,指出了扩展的名字;后面两个参数只是在make和configure执行时用来显示的,所以我们可以随便写。[ ]在autoconf语法中的作用类似于双引号,用来包裹字符串(注意第二个参数中包含了空格,但是可以不用方括号起来)。还有第四个参数用来指明扩展默认是开启还是关闭(yes或no),默认是no。

下面三行其实就是shell语法,判断我们是否开启了PHP_MYEXT2扩展模块。如果开启了该扩展模块(--enable-myext2),则$PHP_MYEXT2变量的值不为no,因此执行PHP_NEW_EXTENSION宏。这个宏函数也是PHP为autoconf定义的扩展语法,第一个参数同样是扩展名称;第二个参数是扩展要编译的C文件,如果有多个,依次写下去就可以了(空格分隔);第三个参数固定是$ext_shared。

接下来编写php_myext2.h头文件,该文件的命名是PHP扩展的规范 ? php_扩展名.h:

 1 #ifndef PHP_MYEXT2_H 2 #define PHP_MYEXT2_H 3  4 extern zend_module_entry myext2_module_entry; 5 #define phpext_myext2_ptr &myext2_module_entry 6  7 #define PHP_MYEXT2_VERSION "0.1.0" 8  9 /* prototypes */10 PHP_FUNCTION(hello);11 12 #endif  /* PHP_MYEXT2_H */

这里主要的代码是定义了名为phpext_myext2_ptr的宏,PHP底层通过该宏来引用我们的扩展。可以看出,该宏的命名同样是有规范的 ? phpext_扩展名_ptr。而myext2_module_entry是我们稍后要在.c文件里定义的结构体,它的命名也是规范的 ? 扩展名_module_entry。

此外我们还定义了一个标识我们扩展版本号的宏和一个函数原型(通过PHP_FUNCTION宏,PHP_FUNCTION宏函数的参数是外部可使用的函数名),稍后我们会来实现这个函数。

最后来看下myext2.c文件的实现:

 1 #include "php.h" 2 #include "php_myext2.h" 3  4 /* {{{ myext2_functions[] 5  * 6  * Every user visible function must have an entry in myext2_functions[]. 7  */ 8 static const zend_function_entry myext2_functions[] = { 9     PHP_FE(hello,       NULL)10     PHP_FE_END11 };12 /* }}} */13 14 /* {{{ myext2_module_entry15  */16 zend_module_entry myext2_module_entry = {17     STANDARD_MODULE_HEADER,18     "myext2",               /* module name */19     myext2_functions,       /* module functions */20     NULL,                   /* module initialize */21     NULL,                   /* module shutdown */22     NULL,                   /* request initialize */23     NULL,                   /* request shutdown */24     NULL,                   /* phpinfo */25     PHP_MYEXT2_VERSION,     /* module version */26     STANDARD_MODULE_PROPERTIES27 };28 /* }}} */29 30 #ifdef COMPILE_DL_MYEXT231 ZEND_GET_MODULE(myext2)32 #endif33 34 /* {{{ proto void hello()35    Print "hello world!" */36 PHP_FUNCTION(hello)37 {38     php_printf("hello world!\n");39 }40 /* }}} */

对比下扩展骨架创建的.c文件就会发现,我们的.c文件非常的简单,其实这些对一个最基本的扩展来说就已经足够了。

上面的代码是简单而清晰的,大部分注释已经很具说明性了。我们再简要概括下:

  1. 开头包含我们要用到的头文件。php.h是必须的,它已经帮我们包含了我们会用到的绝大多数的标准库文件,比如stdio.h,stdlib.h等等。
  2. myext2_functions定义了由我们要暴露出去的函数构成的结构体数组,每一个元素通过PHP_FE宏来指定。PHP_FE宏有两个参数,第一个是外部可使用的函数名,第二个是参数信息(这里我们简单使用了NULL),最后一个元素必须是PHP_FE_END。注意它的注释,再次强调,每一个要暴露给外部使用的函数,都必须在该结构体数组中有定义。
  3. myext2_module_entry定义了我们的模块信息,它是一个结构体,大部分属性都已经通过注释给出了说明。注意中间的五个函数指针,我们都简单的置为了NULL,在后续的博文中会讲述它们的用法。
  4. ZEND_GET_MODULE(myext2)宏函数是被ifdef宏包含的,所以说它是否调用是视情况而定的。至于什么情况下会被调用,什么情况下不会被调用,在后续的博文中会讲述。
  5. 最后几行代码我们实现了hello函数,它很简单,调用php_printf输出hello world!跟一个换行符,php_printf的用法和printf完全一样。
  6. 注释里的 {{{ 和 }}} 是为了方便vim等编辑器折叠而使用的,我们推荐你也这样来写注释。

这里面涉及了一些宏,比如PHP_FE,PHP_FE_END,PHP_FUNCTION等等,完整介绍这些宏要到后续的博文中才可以,眼下最简单的办法就是记住这些宏。

注意到我们每一个文件的命名,变量的命名,空格和缩进,以及注释等都是非常规范的,遵循这些规范,可以使我们编写的代码和PHP本身的代码更加契合,我们也推荐你使用这样的规范来开发PHP扩展。

最后,编译运行我们的扩展:

$ ./buildconf --force$ ./configure --help | grep myext2  --enable-myext2           Enable myext2 support$ ./configure --disable-all --enable-myext2 --enable-debug --enable-maintainer-zts$ make$ php-dev -m | grep myext2myext2$ php-dev -r 'hello();'hello world!

 

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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