Table of Contents
PHP extension development (1): Getting started, php extensions
Home Backend Development PHP Tutorial PHP extension development (1): Getting started, php extension_PHP tutorial

PHP extension development (1): Getting started, php extension_PHP tutorial

Jul 13, 2016 am 10:06 AM
php

PHP extension development (1): Getting started, php extensions

There are many articles and blogs about PHP extension development, the more classic ones are:

I am going to summarize my learning and insights about PHP extension development in this series of blog posts, trying to simply and clearly describe the most basic knowledge that should be possessed to develop a PHP extension under Linux system. My level is low, so there are bound to be mistakes. Please point them out.

Preparation

First, obtain a copy of the PHP source code (you can check it out from Github, or download the latest stable version from the official website), and then compile it. To speed up compilation, we recommend disabling all extra extensions (using the --disable-all option), but it is better to turn on debugging (using the --enable-debug option) and thread safety (using --enable-maintainer-zts), But you need to turn off debugging when publishing the extension, and choose whether to turn on thread safety according to the situation:

$ ./buildconf --<span>force
$ .</span>/configure --disable-all --enable-debug --enable-maintainer-<span>zts
$ </span><span>make</span>
Copy after login

Note that we did not specify the --prefix option (nor make install) as this is not required. Pay attention to the output information. You may need to install some dependency packages to successfully compile PHP.

The compiled PHP executable program is in the sapi directory of the source code. There are different subdirectories corresponding to different host environments. We will mainly use the cli (command line interface) environment in the future. You can create an alias for easy reference:

$ alias php-dev=/usr/local/src/php-<span>5.6</span>.<span>5</span>/sapi/cli/php
Copy after login

There are some command line options that are useful:

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

Extended skeleton

All official extensions of PHP are in the ext directory of the source code. Extensions we write ourselves can also be placed in this directory. Note that there is a shell script named ext_skel in this directory, which is used to generate a PHP extension skeleton. Using this script can help us quickly create a PHP extension:

$ ./ext_skel --extname=myext
Copy after login

The above command helps us create an extension named myext, and the source code is in the myext directory. Executing the script without any parameters prints help information so you can see more options provided by the script.

Next let’s finalize our extension. Enter the myext directory, edit the config.m4 configuration file, find the PHP_ARG_ENABLE macro function, and remove the previous dnl comment (three lines in total). Return to the source code root directory and re-execute the buildconf, configure and make commands:

$ ./buildconf --<span>force
$ .</span>/configure --help | <span>grep</span><span> myext
    </span>--enable-<span>myext           Enable myext support
$ .</span>/configure --disable-all --enable-myext --enable-debug --enable-maintainer-<span>zts
$ </span><span>make</span>
Copy after login

Note that we used ./configure --help | grep myext to print the loading status of our extension. If you cannot see the following output, it means that our extension was not configured successfully. Go back and check the config.m4 file.

This compilation should be very fast since most of the code has already been compiled. PHP has another way to compile extensions (using dynamic linking to compile the extension into a .so file), but we recommend using static compilation when developing extensions, because this eliminates the need to load the extension in the configuration file. steps.

If all goes well, our first extension will be ready to execute:

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

The first command shows that our extension has been loaded. The second command executes the function that the ext_skel extension skeleton automatically created for us. Of course, this function is meaningless, but we can easily adapt this function to hello world.

Manually create extensions

Most tutorials use the ext_skel extension skeleton as a prototype to describe extension development. This approach is of course very convenient and fast. But I personally prefer to develop extensions purely by hand, because it is easier to understand every detail.

To create an extension manually, first enter the ext directory and create our extension directory myext2. Several files are required: config.m4, myext2.c and php_myext2.h.

First, let’s write the configuration file config.m4:

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

Config.m4 is actually the configuration file used by the autoconf program. Autoconf is an important component in the autotools toolbox. It would take a long time to fully introduce the usage of autoconf. Fortunately, the usage here is very simple.

PHP_ARG_ENABLE is a macro function defined by PHP for autoconf. Myext2 is its first parameter, indicating the name of the extension; the latter two parameters are only used to display when make and configure are executed, so we can write whatever we want. [ ] functions like double quotes in autoconf syntax, used to wrap strings (note that the second parameter contains spaces, but it does not need to be enclosed in square brackets). There is also a fourth parameter used to indicate whether the extension is on or off by default (yes or no). The default is no.

The following three lines are actually shell syntax to determine whether we have enabled the PHP_MYEXT2 extension module. If the extension module is enabled (--enable-myext2), the value of the $PHP_MYEXT2 variable is not no, so the PHP_NEW_EXTENSION macro is executed. This macro function is also the extension syntax defined by PHP for autoconf. The first parameter is also the extension name; the second parameter is the C file to be compiled by the extension. If there are multiple, just write them down in sequence (separated by spaces); The three parameters are fixed to $ext_shared.

Next, write the php_myext2.h header file. The naming of this file is the specification of the PHP extension - php_extension.h:

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

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

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

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

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

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

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

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

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

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

$ ./buildconf --<span>force
$ .</span>/configure --help | <span>grep</span><span> myext2
  </span>--enable-<span>myext2           Enable myext2 support
$ .</span>/configure --disable-all --enable-myext2 --enable-debug --enable-maintainer-<span>zts
$ </span><span>make</span><span>

$ php</span>-dev -m | <span>grep</span><span> myext2
myext2
$ php</span>-dev -r <span>'</span><span>hello();</span><span>'</span><span>
hello world</span>!
Copy after login

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/960240.htmlTechArticlePHP扩展开发(1):入门,php扩展 有关PHP扩展开发的文章、博客已经很多了,比较经典的有: 我准备在此系列博文中总结我有关PHP扩展开发...
Statement of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles