Table of Contents
Learning of PHP kernel--Creating PHP extensions
Home Backend Development PHP Tutorial Learning the PHP kernel--Creating PHP extensions_PHP tutorial

Learning the PHP kernel--Creating PHP extensions_PHP tutorial

Jul 13, 2016 am 09:57 AM
Kernel

Learning of PHP kernel--Creating PHP extensions

One of the main reasons for PHP's success is the large number of extensions available. No matter what needs web developers have, they are most likely to be found in PHP distribution packages. The PHP distribution package includes many extensions that support various databases, graphics file formats, compression, and XML technology extensions.
The introduction of extension API has made great progress in PHP3. The extension API mechanism allows the PHP development community to easily develop dozens of extensions. Now, two versions later, the API is still very similar to PHP3. The main idea of ​​extensions is to hide the internal mechanisms of PHP and the scripting engine itself from extension writers as much as possible, and only require developers to be familiar with the API.
There are two reasons to write your own PHP extension. The first reason is: PHP needs to support a technology that it does not yet support. This usually involves wrapping some off-the-shelf C library to provide a PHP interface. For example, if a database called FooBase is launched on the market, you need to create a PHP extension to help you call FooBase's C function library from PHP. This work might be done by just one person and then shared by the entire PHP community (if you will). The second, less common reason is that you need to write some business logic for performance or functionality reasons.
Suppose you are developing a website and need a function that repeats a string n times. The following is an example written in PHP:
function util_str_repeat($string, $n){
$result = "";
for($i = 0; $i < $n; $i ){
$result .= $string;
}
return $result;
}
util_str_repeat("One", 3);// returns "OneOneOne".
util_str_repeat("One", 1);// returns "One".
Suppose that for some strange reasons, you need to call this function from time to time, and you also need to pass a long string and a large value n to the function. This means that there is a considerable amount of string concatenation and memory reallocation in the script, which can significantly slow down script execution. If there was a function that could faster allocate a large and sufficient memory to store the result string, and then repeat $string n times, there would be no need to allocate memory on each loop iteration.
The first step to create a function for the extension is to write a function definition file, which defines the function prototype provided by the extension. In this example, there is only one line to define the function prototype util_str_repeat():
string util_str_repeat(string str, int n)
The general format of a function definition file is one function per line. You can define optional parameters and use a large number of PHP types, including: bool, float, int, array, etc.
Save it as a util.def file in the PHP original code directory tree (that is, put it in the same directory as the ext_skel file, my directory is /usr/share/php5/).
Then it’s time to run the function definition file by extending the skeleton constructor. The constructor script is ext_skel. Assuming you save your function definitions in a file called util.def, and you want to name your extension util, run the following command to create the extension skeleton:
sudo ./ext_skel --extname=util --proto=util.def
After execution, I reported the following error:
./ext_skel: 1: cd: can't cd to /usr/lib/php5/skeleton
Creating directory util
awk: cannot open /create_stubs (No such file or directory)
Creating basic files: config.m4 config.w32 .svnignore util.c./ext_skel: 216: ./ext_skel: cannot open /skeleton.c: No such file
php_util.h./ext_skel: 234: ./ext_skel: cannot open /php_skeleton.h: No such file
CREDITS./ext_skel: 238: ./ext_skel: cannot open /CREDITS: No such file
EXPERIMENTAL./ext_skel: 242: ./ext_skel: cannot open /EXPERIMENTAL: No such file
tests/001.phpt./ext_skel: 247: ./ext_skel: cannot open /tests/001.phpt: No such file
util.php./ext_skel: 251: ./ext_skel: cannot open /skeleton.php: No such file
rm: cannot remove ‘function_entries’: No such file or directory
rm: cannot remove ‘function_declarations’: No such file or directory
rm: cannot remove ‘function_stubs’: No such file or directory
[done].
To use your new extension, you will have to execute the following steps:
1. $ cd ..
2. $ vi ext/util/config.m4
3. $ ./buildconf
4. $ ./configure --[with|enable]-util
5. $ make
6. $ ./php -f ext/util/util.php
7. $ vi ext/util/util.c
8. $ make
Repeat steps 3-6 until you are satisfied with ext/util/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
Obviously the path to /usr/lib/php5/skeleton is wrong. Edit the ext_skel file, change /usr/lib/php5/skeleton to /usr/share/php5/skeleton, and then remove the generated util file. folder and execute the previous command again. After success, the prompt is as follows:
Creating directory util
Creating basic files: config.m4 config.w32 .svnignore util.c php_util.h CREDITS EXPERIMENTAL tests/001.phpt util.php [done].
To use your new extension, you will have to execute the following steps:
1. $ cd ..
2. $ vi ext/util/config.m4
3. $ ./buildconf
4. $ ./configure --[with|enable]-util
5. $ make
6. $ ./php -f ext/util/util.php
7. $ vi ext/util/util.c
8. $ make
Repeat steps 3-6 until you are satisfied with ext/util/config.m4 and
step 6 confirms that your module is compiled into PHP. Then, start writing
code and repeat the last two steps as often as necessary.
Then compile the extension using static compilation. In order for the extension to be compiled, the config.m4 file in the extension directory util/ needs to be modified. The extension does not wrap any external C library, you need to add support for the --enable-util configuration switch to the PHP build system (the --with-extension switch is used for extensions that require the user to specify the path to the relevant C library). Found the following:
dnl PHP_ARG_ENABLE(util, whether to enable util support,
dnl Make sure that the comment is aligned:
dnl [ --enable-util           Enable util support])
Remove the previous dnl and modify it to the following result:
PHP_ARG_ENABLE(util, whether to enable util support,
Make sure that the comment is aligned:
[ --enable-util         Enable util support])
Then modify the util.c file and find the following code:
PHP_FUNCTION(util_str_repeat)
{
char *str = NULL;
int argc = ZEND_NUM_ARGS();
int str_len;
long n;
if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE)
return;
php_error(E_WARNING, "util_str_repeat: not implemented yet");
}
Modify it to the following code:
PHP_FUNCTION(util_str_repeat)
{
char *str = NULL;
int argc = ZEND_NUM_ARGS();
int str_len;
long n;
char *result; /* Points to resulting string */
char *ptr; /* Points at the next location we want to copy to */
int result_length; /* Length of resulting string */
if (zend_parse_parameters(argc TSRMLS_CC, "sl", &str, &str_len, &n) == FAILURE)
return;
/* Calculate length of result */
result_length = (str_len * n);
/* Allocate memory for result */
result = (char *) emalloc(result_length 1);
/* Point at the beginning of the result */
ptr = result;
while (n--) {
/* Copy str to the result */
memcpy(ptr, str, str_len);
/* Increment ptr to point at the next position we want to write to */
ptr = str_len;
}
/* Null terminate the result. Always null-terminate your strings
even if they are binary strings */
*ptr = '
/* Return result to the scripting engine without duplicating it*/
RETURN_STRINGL(result, result_length, 0);
}
I won’t talk about the specific content here, I will write about it later.
Then it’s compilation and installation. In the util directory, the command is as follows (sudo may be required for each command):
phpize
./configure
make
make test
make install
Then configure the generated extension file. In the php5.5 version, go to the /etc/php5/mods-available directory, create the util.ini file, and write the following content:
extension=util.so
Then enable util extension
sudo php5enmod util
Finally, restart php-fpm
sudo service php5-fpm restart
Create a php file and test it. The test file is as follows:
for ($i = 1; $i <= 3; $i ) {
print util_str_repeat("CraryPrimitiveMan ", $i);
print "n";
}
?>
The execution results are as follows:
CraryPrimitiveMan
CraryPrimitiveMan CraryPrimitiveMan
CraryPrimitiveMan CraryPrimitiveMan CraryPrimitiveMan
In this way we have successfully created an extension containing a simple PHP function.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/984112.htmlTechArticleLearning of PHP Core--Creating PHP Extensions One of the main reasons for PHP's success is that it has a large number of available Extension. No matter what needs web developers have, such needs are most likely to be developed in 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)
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)

How to install the Linux kernel on Ubuntu 22.04 Detailed tutorial! How to install the Linux kernel on Ubuntu 22.04 Detailed tutorial! Mar 01, 2024 pm 10:34 PM

To install the Linux kernel on Ubuntu22.04, you can follow the following steps: Update the system: First, make sure your Ubuntu system is the latest, execute the following command to update the system package: sudoaptupdatesudoaptupgrade Download the kernel file: Visit the official Linux kernel website () to download Required kernel version. Select a stable version and download the source code file (with .tar.gz or .tar.xz extension), for example: wget Unzip the file: Use the following command to unzip the downloaded kernel source code file: tar-xflinux-5.14.tar. xz install build dependencies: Install the tools and dependencies required to build the kernel. Execute

Modify Linux kernel startup sequence Modify Linux kernel startup sequence Feb 23, 2024 pm 10:22 PM

Modify the kernel startup sequence of Linux 1. Modify the kernel startup sequence of RHEL6/CentOS6. Check the /etc/grub.conf file to determine the system kernel situation. According to the document, there are two kernel versions in the system, namely 2.6.32-573.18.1.el6.x86_64 and 2.6.32-431.23.3.el6.x86_64. Kernel versions are listed from top to bottom. In the grub.conf file, you can decide which kernel version to use when the system starts by adjusting the default parameters. The default value is 0, which means the system will boot the latest kernel version. A value of 0 corresponds to the first content listed in the grub.conf file.

Is the Android system based on the Linux kernel? Is the Android system based on the Linux kernel? Mar 14, 2024 pm 03:12 PM

Is the Android system based on the Linux kernel? Android system, as one of the most widely used mobile operating systems in the world, has always been said to be developed based on the Linux kernel. However, what is the real situation? Let’s explore this issue. First, let's understand the Linux kernel. The Linux kernel, as an open source operating system kernel, was first released by Linus Torvalds in 1991. It provides a good foundation for many operating systems, including And

Linux kernel main function analysis and analysis Linux kernel main function analysis and analysis Mar 14, 2024 am 11:27 AM

Linux kernel main function analysis and analysis The Linux kernel is a large and complex system, in which the main function plays a vital role. It is the entry point of the entire system and is responsible for initializing various subsystems, drivers and kernel modules. Finally start the entire operating system. This article will analyze and analyze the main function of the Linux kernel, and demonstrate its key functions and execution flow through specific code examples. In the Linux kernel, the entry point of the main function is start_k in the init/main.c file.

Explore the programming languages ​​used under the hood of the Linux kernel Explore the programming languages ​​used under the hood of the Linux kernel Mar 20, 2024 am 08:06 AM

Title: Exploring the programming language used at the bottom of the Linux kernel. As an open source, stable and reliable operating system kernel, the Linux kernel has a wide range of applications in the computer field. To have an in-depth understanding of the Linux kernel, you have to involve the programming language used at the bottom. In fact, the Linux kernel is mainly written in C language, which is an efficient, flexible and easy-to-maintain programming language that is very suitable for operating system development. This article will explore the bottom of the Linux kernel from a detailed perspective

Detailed explanation of Linux kernel source code storage location Detailed explanation of Linux kernel source code storage location Mar 14, 2024 pm 06:12 PM

Detailed explanation of the storage location of Linux kernel source code. Linux kernel source code is the core part of the Linux operating system. It contains the implementation code for various functions of the operating system. To understand where the Linux kernel source code is stored, we first need to understand the organizational structure of the Linux kernel. Linux kernel source code is usually stored in the /usr/src/linux or /usr/src/linux- directory. In this directory, there are many

Ubuntu compilation and installation kernel tutorial. Ubuntu compilation and installation kernel tutorial. Feb 19, 2024 pm 02:54 PM

Compiling and installing the Ubuntu kernel requires certain professional skills and practical experience. Here are the general steps, but please proceed with caution as this process may carry certain risks. Before you begin, be sure to back up important data and systems. Get the source code: Visit the Ubuntu official website () or the kernel developer website () to download the latest kernel source code. Unzip the source code to a suitable directory, such as /usr/src. Install compilation dependencies: Install the dependencies required to build the kernel. Open a terminal and execute the following command: sudoapt-getinstallbuild-essentiallibncurses-devbisonflexlibssl-devlibelf-d

CentOS 7 kernel upgrade tutorial. CentOS 7 kernel upgrade tutorial. Feb 18, 2024 pm 05:33 PM

Upgrading the kernel on CentOS7 requires the following steps: Check the current kernel version: Open a terminal and run the following command: uname -r Add ELRepo source: Run the following command to add the ELRepo source: rpm --import Install new kernel: Run the following command to install Latest stable kernel: yum --enablerepo=elrepo-kernelinstallkernel-ml Update boot manager (GRUB) configuration: Run the following command to update the GRUB configuration file: grub2-mkconfig -o/boot/grub2/grub.cfg Restart the system: Run The following command is used to restart the system: reboot verification

See all articles