Table of Contents
An introductory tutorial on PHP extension development
Home Backend Development PHP Tutorial Introduction to PHP extension development tutorial_PHP tutorial

Introduction to PHP extension development tutorial_PHP tutorial

Jul 13, 2016 am 10:06 AM
l php main use Getting Started Tutorial exist develop Expand article language

An introductory tutorial on PHP extension development

This article mainly introduces an introductory tutorial on PHP extension development. This article explains the most basic requirements for developing a PHP extension under the Linux system using C language. Basic knowledge, friends in need can refer to it

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

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:

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:

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

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:

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:

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

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:

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:

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:

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");
}
/* }}} */

Comparing the .c files created by the extended skeleton, you will find that our .c files are very simple. In fact, these are enough for a most basic extension.

The code above is simple and clear, and most of the comments are already very descriptive. Let’s briefly summarize it:

1. The beginning contains the header files we want to use. php.h is necessary, it has helped us include most of the standard library files we will use, such as stdio.h, stdlib.h, etc.
2.myext2_functions defines a structure array composed of the functions we want to expose. Each element is specified through the PHP_FE macro. The PHP_FE macro has two parameters, the first is the externally usable function name, the second is parameter information (here we simply use NULL), and the last element must be PHP_FE_END. Pay attention to its comments. Again, every function that is to be exposed to external use must be defined in the structure array.
3.myext2_module_entry defines our module information. It is a structure and most of the attributes have been explained through comments. Pay attention to the five function pointers in the middle. We simply set them to NULL. Their usage will be described in subsequent blog posts.
4. The ZEND_GET_MODULE (myext2) macro function is included by the ifdef macro, so whether it is called depends on the situation. As for the circumstances under which it will be called and the circumstances under which it will not be called, I will describe it in a subsequent blog post.
5. In the last few lines of code, we implemented the hello function. It is very simple. Call php_printf to output hello world! with a newline character. The usage of php_printf is exactly the same as printf.
6. {{{ and }}} in comments are used to facilitate folding in editors such as vim. We recommend that you write comments in this way.
This involves some macros, such as PHP_FE, PHP_FE_END, PHP_FUNCTION, etc. A complete introduction to these macros will be provided in subsequent blog posts. The easiest way right now is to remember these macros.

Notice that the naming of each of our files, the naming of variables, spaces and indentations, and comments are very standardized. Following these specifications can make the code we write more consistent with the code of PHP itself. We also It is recommended that you use such specifications to develop PHP extensions.

Finally, compile and run our extension:

The code is as follows:


$ ./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/961082.htmlTechArticleAn introductory tutorial on PHP extension development. This article mainly introduces an introductory tutorial on PHP extension development. This article explains how to use C language to The most basic knowledge you should have to develop a PHP extension under Linux system requires...
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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks 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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

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

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

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

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles