Introduction to develop our own PHP extension. In this exercise, I’m going to use Fedora Linux.
Prepare build environment and requirement.
# yum groupinstall "Development Tools"
# yum install php-devel php-cli
and this will install all development dependencies.
Steps to produce PHP Extension HelloWorld.
Step 1 : create extension directory.
# mkdir php_ext_helloworld
# cd php_ext_helloworld
Step 2: make 3 files with the code.
File: config.m4
PHP_ARG_ENABLE(php_helloworld, Whether to enable the HelloWorldPHP extension, [ --enable-helloworld-php Enable HelloWorldPHP])
if test "$PHP_HELLOWORLD" != "no"; then
PHP_NEW_EXTENSION(php_helloworld, php_helloworld.c, $ext_shared)
fi
File: php_helloworld.h
// we define Module constants
#define PHP_HELLOWORLD_EXTNAME "php_helloworld"
#define PHP_HELLOWORLD_VERSION "0.0.1"
// then we declare the function to be exported
PHP_FUNCTION(helloworld_php);
File : php_helloworld.c
// include the PHP API itself
#include
// then include the header of your extension
#include "php_helloworld.h"
// register our function to the PHP API
// so that PHP knows, which functions are in this module
zend_function_entry helloworld_php_functions[] = {
PHP_FE(helloworld_php, NULL)
{NULL, NULL, NULL}
};
// some pieces of information about our module
zend_module_entry helloworld_php_module_entry = {
STANDARD_MODULE_HEADER,
PHP_HELLOWORLD_EXTNAME,
helloworld_php_functions,
NULL,
NULL,
NULL,
NULL,
NULL,
PHP_HELLOWORLD_VERSION,
STANDARD_MODULE_PROPERTIES
};
// use a macro to output additional C code, to make ext dynamically loadable
ZEND_GET_MODULE(helloworld_php)
// Finally, we implement our "Hello World" function
// this function will be made available to PHP
// and prints to PHP stdout using printf
PHP_FUNCTION(helloworld_php) {
php_printf("Hello World! (from our extension)\n");
}
Step 3: build it.
inside the current working directory (php_ext_helloworld).
# phpize
# ./configure --enable-php-helloworld
# make
# make install
Step 4: Test
test the new extension.
# php -d extension=php_helloworld.so -r 'helloworld_php();'
Finish.
p/s: tested on Fedora Linux with PHP 7.3
Building on windows note.
change config.m4 to config.w32 and the content of the file to …
ARG_ENABLE("helloworld", "helloworld support", "yes");
if (PHP_HELLOWORLD == "yes") {
EXTENSION("helloworld", "php_helloworld.c");
}
to build it, use nmake
to replace make
.
Done.
credits to :
Jens A. Koch (https://stackoverflow.com/users/1163786/jens-a-koch)
Good References:
https://www.php.net/manual/en/internals2.structure.php
https://web.archive.org/web/20111101050807/http://devzone.zend.com/article/1021
https://www.sitepoint.com/developing-php-extensions-c-php-cpp-advanced/