search
HomeBackend DevelopmentPHP TutorialPHP extension development introductory tutorial, php extension introductory tutorial_PHP tutorial

Introductory tutorial on PHP extension development, introductory tutorial on php extension

PHP extension development

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, you need to 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:

Copy code The code is as follows:

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

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:

Copy code The code is as follows:

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

There are some command line options that are useful:

Copy code The code is as follows:

php-dev -h      # Print help information
php-dev -v     # Print version information
php-dev --ini      #Print configuration information     
php-dev -m     #Print loaded module information
php-dev -i      # phpinfo
php-dev -r     #Execute the code in code<br>

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:

Copy code The code is as follows:

$ ./ext_skel --extname=myext

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:

Copy code The code is as follows:

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

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 because 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:

Copy code The code is as follows:

$ php-dev -m | grep myext
myext
$ 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.

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:

Copy code The code is as follows:

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 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:

Copy code The code is as follows:

#ifndef PHP_MYEXT2_H
#define PHP_MYEXT2_H

extern zend_module_entry myext2_module_entry;
#define phpext_myext2_ptr &myext2_module_entry

#define PHP_MYEXT2_VERSION "0.1.0"

/* prototypes */
PHP_FUNCTION(hello);

#endif /* PHP_MYEXT2_H */

The main code here is to define a macro named phpext_myext2_ptr. The bottom layer of PHP refers to our extension through this macro. It can be seen that the naming of this macro is also standardized - phpext_extension_ptr. Myext2_module_entry is a structure that we will define in the .c file later, and its naming is also standardized - extension _module_entry.

In addition, we also defined a macro that identifies our extended version number and a function prototype (through the PHP_FUNCTION macro, the parameter of the PHP_FUNCTION macro function is the externally usable function name). We will implement this function later.

Finally, let’s look at the implementation of the myext2.c file:

Copy code The code is as follows:

#include "php.h"
#include "php_myext2.h"

/* {{{ myext2_functions[]
 *
 * Every user visible function must have an entry in myext2_functions[].
 */
static const zend_function_entry myext2_functions[] = {
    PHP_FE(hello,       NULL)
    PHP_FE_END
};
/* }}} */

/* {{{ myext2_module_entry
 */
zend_module_entry myext2_module_entry = {
    STANDARD_MODULE_HEADER,
    "myext2",               /* module name */
    myext2_functions,       /* module functions */
    NULL,                   /* module initialize */
    NULL,                   /* module shutdown */
    NULL,                   /* request initialize */
    NULL,                   /* request shutdown */
    NULL,                   /* phpinfo */
    PHP_MYEXT2_VERSION,     /* module version */
    STANDARD_MODULE_PROPERTIES
};
/* }}} */

#ifdef COMPILE_DL_MYEXT2
ZEND_GET_MODULE(myext2)
#endif

/* {{{ proto void hello()
   Print "hello world!" */
PHP_FUNCTION(hello)
{
    php_printf("hello world!n");
}
/* }}} */

对比下扩展骨架创建的.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 myext2
myext2
$ php-dev -r 'hello();'
hello world!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/960703.htmlTechArticlePHP extension development introductory tutorial, php extension introductory tutorial PHP extension development I plan to summarize my knowledge about PHP in this series of blog posts The learning and insights of extended development are tried to be described simply and clearly in L...
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.