search
HomeBackend DevelopmentPHP TutorialIntroduction to PHP extension development tutorial_PHP tutorial

Introduction to PHP extension development tutorial_PHP tutorial

Jul 13, 2016 am 10:06 AM
lphpmainuseGetting Started TutorialexistdevelopExpandarticlelanguage

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 <p> </p> <p>Extended skeleton</p> <p>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: </p> <p>The code is as follows:</p> <div id="code79500"> <br> $ ./ext_skel --extname=myext <br> 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. <p> </p> <p>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: </p> <p>The code is as follows:</p> <div id="code60938"> <br> $ ./buildconf --force<br> $ ./configure --help | grep myext<br> --enable-myext Enable myext support<br> $ ./configure --disable-all --enable-myext --enable-debug --enable-maintainer-zts<br> $ make <p> </p> <p>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. </p> <p>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. </p> <p>If all goes well, our first extension will be ready to execute: </p> <p>The code is as follows:</p> <div id="code43184"> <br> $ php-dev -m | grep myext<br> myext<br> $ php-dev -r 'echo confirm_myext_compiled("myext") . "n";'<br> Congratulations! You have successfully modified ext/myext/config.m4. Module myext is now compiled into PHP. <br> 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. <p> </p> <p>Manually create extensions</p> <p>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. </p> <p>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. </p> <p>First, let’s write the configuration file config.m4: </p> <p>The code is as follows:</p> <div id="code69887"> <br> PHP_ARG_ENABLE(myext2, whether to enable myext2 support,<br> [ --enable-myext2 Enable myext2 support]) <p> </p> <p>if test "PHP_MYEXT2" != "no"; then<br> PHP_NEW_EXTENSION(myext2, myext2.c, $ext_shared)<br> fi</p> <br> 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. <p> </p> <p>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. </p> <p>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. </p> <p>Next, write the php_myext2.h header file. The naming of this file is the specification of the PHP extension - php_extension.h: </p> <p>The code is as follows:</p> <div id="code89777"> <br> #ifndef PHP_MYEXT2_H<br> #define PHP_MYEXT2_H <p> </p> <p>extern zend_module_entry myext2_module_entry;<br> #define phpext_myext2_ptr &myext2_module_entry</p> <p>#define PHP_MYEXT2_VERSION "0.1.0"</p> <p>/* prototypes */<br> PHP_FUNCTION(hello);</p> <p>#endif /* PHP_MYEXT2_H */</p> <p> </p> <p>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. </p> <p>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. </p> <p>Finally, let’s look at the implementation of the myext2.c file: </p> <p>The code is as follows:</p> <div id="code56665"> <br> #include "php.h"<br> #include "php_myext2.h" <p> </p> <p>/* {{{ myext2_functions[]<br> *<br> * Every user visible function must have an entry in myext2_functions[].<br> */<br> static const zend_function_entry myext2_functions[] = {<br> PHP_FE(hello, NULL)<br> PHP_FE_END<br> };<br> /* }}} */</p> <p>/* {{{ myext2_module_entry<br> */<br> zend_module_entry myext2_module_entry = {<br> STANDARD_MODULE_HEADER,<br> "myext2", /* module name */<br> myext2_functions, /* module functions */<br> NULL, /* module initialize */<br> NULL, /* module shutdown */<br> NULL, /* request initialize */<br> NULL, /* request shutdown */<br> NULL, /* phpinfo */<br> PHP_MYEXT2_VERSION, /* module version */<br> STANDARD_MODULE_PROPERTIES<br> };<br> /* }}} */</p> <p>#ifdef COMPILE_DL_MYEXT2<br> ZEND_GET_MODULE(myext2)<br> #endif</p> <p>/* {{{ proto void hello()<br> Print "hello world!" */<br> PHP_FUNCTION(hello)<br> {<br> php_printf("hello world!n");<br> }<br> /* }}} */</p> <p> </p> <p>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. </p> <p>The code above is simple and clear, and most of the comments are already very descriptive. Let’s briefly summarize it: </p> <p>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. <br> 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. <br> 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. <br> 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. <br> 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. <br> 6. {{{ and }}} in comments are used to facilitate folding in editors such as vim. We recommend that you write comments in this way. <br> 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. </p> <p>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. </p> <p>Finally, compile and run our extension: </p> <p>The code is as follows:</p> <div id="code56002"> <br> $ ./buildconf --force<br> $ ./configure --help | grep myext2<br> --enable-myext2 Enable myext2 support<br> $ ./configure --disable-all --enable-myext2 --enable-debug --enable-maintainer-zts<br> $ make <p> </p> <p>$ php-dev -m | grep myext2<br> myext2<br> $ php-dev -r 'hello();'<br> hello world!</p> <p align="left"></p> <div style="display:none;"> <span id="url" itemprop="url">http://www.bkjia.com/PHPjc/961082.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/961082.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">An 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...</span> </div> </div> <div class="art_confoot"></div> </div> </div> </div> </div> </div> </div>
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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools